const Router = require('koa-router');
const playerCtl= require('../../controllers/players.js')
const eventCtl= require('../../controllers/events.js')
const matchCtl= require('../../controllers/matches.js')
const teamCtl= require('../../controllers/teams.js')
const plyfeaCtl= require('../../controllers/playerfeatures.js')
const cmptCtl= require('../../controllers/competitions.js')
const MplCtl= require('../../controllers/matchplayers.js')
const router = new Router();
const mongoose = require('mongoose');
const {Schema, model} = mongoose;

/**
 * @swagger
 * tags:
 *   - name: player
 *     description: Everything about player
 */

router
/**
 * @swagger
 * paths:
 *   /players:
 *     get:
 *       tags:
 *         - player
 *       summary: Return a list of players
 *       description: ''
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             type: array
 *             items:
 *               $ref: '#/definitions/player'
 */
    .get('/', async (ctx, next)=>{ ctx.body = await playerCtl.list(); })

/**
 * @swagger
 * paths:
 *   /players:
 *     post:
 *       tags:
 *         - player
 *       summary: Create a player
 *       description: ''
 *       parameters:
 *         - in: body
 *           name: "body"
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/player"
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .post('/', async (ctx, next)=>{
        const {id} = ctx.params;
        const data = ctx.request.body;
        for(let key of Object.keys(data)){
            let a = data[key]
            const  r = await playerCtl.create(a);
            //console.log(a)
        }
    })
/**
 * @swagger
 * paths:
 *   /players/{cid}:
 *     get:
 *       tags:
 *         - player
 *       summary: Return a player
 *       description: ''
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             $ref: '#/definitions/player'
 */
    .get('/:id', async (ctx, next)=>{
        // Retrieves informations about a given player
        const {id} = ctx.params;
        const r = await playerCtl.retrieve(id);
        ctx.assert(r !== null, 404, 'Detail not found!');
        //console.log(r.currentTeamName);
        const T = await teamCtl.retrieve(r.currentTeamId);
        //console.log(T.name);
        for(let a of T){
            r.currentTeamName = a.name
        }
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /players/{cid}:
 *     put:
 *       tags:
 *         - player
 *       summary: Update or create a player
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *         - in: body
 *           name: body
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/player"
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .put('/:id', async (ctx, next)=>{
        const id = ctx.params.id;
        const data = ctx.request.body;
        const r = await playerCtl.upsert(id, data);
        
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /players/{cid}:
 *     delete:
 *       tags:
 *         - player
 *       summary: Delete a player
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         204:
 *           description: No content
 */
    .delete('/:id', async (ctx, next)=>{
        playerCtl.removeById(ctx.params.id);
        ctx.status = 204;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}/seasons:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return the list of seasons of the given competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:id/seasons', async (ctx, next)=>{
        const {id} = ctx.params;
        ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);
    })

    .get('/playerInfor/:seasonid/:playerid', async (ctx, next)=>{
        const {seasonid, playerid} = ctx.params;
        const player = await playerCtl.find({playerId: playerid})
        //console.log(player)
        let result = [];
        for (let a of player) {
            let obj = {};
            obj.playerId = a.playerId;
            obj.playerName = a.playerName;
            obj.playerImg = a.playerImg;
            switch (a.role) {
                case 'GK':
                    obj.position = '门将';
                    break;
                case 'DF':
                    obj.position = '后卫';
                    break;
                case 'MF':
                    obj.position = '中场';
                    break;
                case 'ST':
                    obj.position = '前锋';
                    break;
                default:
                    break;
            }
            obj.birthday = a.birth_date;
            obj.height = a.height;
            obj.weight = a.weight;
            obj.country = a.country;
            obj.countryLogo = a.countryImg;
            for (let key of Object.keys(a.team)) {
                if (key == seasonid) {
                    let teaminf = a.team[key]
                    obj.playerNum = teaminf.teamNum;
                    const teamInfor = await teamCtl.find({teamId: teaminf.teamId})
                    for (let b of teamInfor) {
                        for (let key4 of Object.keys(b['name'])){
                            if (key4 == seasonid){
                                let c = b['name'][key4]
                                obj.club = c.offcialName.slice(0,4);
                                obj.clubLogo = c.teamImg;
                            }
                            else {
                                continue;
                            }
                        }
                    }
                }
                else {
                    continue;
                }
            }
            result.push(obj);
        }
        ctx.body = result;
    })
/**
 * @swagger
 * paths:
 *   /players/{playerid}/actions:
 *     parameters:
 *       - in: path
 *         name: playerid
 *         schema:
 *           type: string
 *         required: true
 *         description: The player ID.
 *     get:
 *       summary: Return the list of the given matches' events of the given player
 *       description: ""
 *       parameters:
 *         - in: query
 *           name: matchId 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:playerid/actions', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const {matchId} = ctx.query;
        //const r = await eventCtl.retrieve(playerid);
        const r = await eventCtl.find({playerId:playerid, matchId});
        //console.log(r)
        //let bisai = [];
        var result = [];
        for(let d of r) { result.push(d)}
        //console.log(result)*/
        /**for(let round of r) {
            console.log(round.constructor)
            for(let key of Object.keys(round)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(round[key] == matchId){
                    //for(let d of round) { bisai.push(d)}
                    bisai.push(round)
                    console.log(bisai)
                }
                else { continue;}
            }
        }
        for(let a of bisai) {
            //console.log(a.constructor)
            for(let key of Object.keys(a)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(a[key] == 'Pass'){
                    //for(let d of round) { bisai.push(d)}
                    result.push(a)
                    console.log(result)
                }
                else { continue;}
            }
        }*/
        let resultOne={};//                     an 1H,2H,fen eventResult
        resultOne['1Hwon'] = [];resultOne['1Hlost'] = [];
        resultOne['2Hwon'] = [];resultOne['2Hlost'] = [];
        //console.log(result)

        for(let key of Object.keys(result)) {
            //console.log(b.constructor)
            //result[b['matchPeroid']].push(b);
            let match = result[key]
            if(match.matchPeriod=='1H'&&match.eventResults=='Won'){
                resultOne['1Hwon'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Accurate'){
                resultOne['1Hwon'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Lost'){
                resultOne['1Hlost'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Not accurate'){
                resultOne['1Hlost'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Neutral'){
                resultOne['1Hlost'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Won'){
                resultOne['2Hwon'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Accurate'){
                resultOne['2Hwon'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Lost'){
                resultOne['2Hlost'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Not accurate'){
                resultOne['2Hlost'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Neutral'){
                resultOne['2Hlost'].push(match);
            }
            else {console.log('error');}
        }
        let actions = {}//                   qv 坐标
        actions['firstHalfwon'] = []
        actions['firstHalflost']= []
        actions['secondHalfwon'] = []
        actions['secondHalflost'] = []

        for(let key of Object.keys(resultOne)){
            //console.log('key:',key);
            if(key=='1Hwon'){
                for(let item of resultOne[key]){
                    let obj = {}
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    actions['firstHalfwon'].push(obj);           //对象直接.xxxx赋值添加
                }
            }
            if(key=='1Hlost'){
                for(let item of resultOne[key]){
                    let obj = {}
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    actions['firstHalflost'].push(obj);
                }
            }
            if(key=='2Hwon'){
                for(let item of resultOne[key]){
                    let obj = {}
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    actions['secondHalfwon'].push(obj);
                }
            }
            if(key=='2Hlost'){
                for(let item of resultOne[key]){
                    let obj = {}
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    actions['secondHalflost'].push(obj);
                }
            }
        }
        
        ctx.body=actions
        //console.log("a",ctx.body)
        /**ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);*/
    })

/**
 * @swagger
 * paths:
 *   /players/{playerid}/events:
 *     parameters:
 *       - in: path
 *         name: playerid
 *         schema:
 *           type: string
 *         required: true
 *         description: The player ID.
 *     get:
 *       summary: Return the list of the given matches' the given events of the given player
 *       description: ""
 *       matchParam:
 *         - in: query
 *           name: matchId 
 *           description: ""
 *           required: true
 *           type: string
 *       eventParam:
 *         - in: query
 *           name: eventId 
 *           description: ""
 *           required: true
 *           type: string
 *       
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:playerid/events', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const {matchId, eventId} = ctx.query;
        //const r = await eventCtl.retrieve(playerid);
        const r = await eventCtl.find({playerId:playerid, matchId, eventId});
        //console.log(r)
        //let bisai = [];
        var result = [];
        for(let d of r) { result.push(d)}
        let resultOne={};
        resultOne['1Hact'] = [];resultOne['1Hnact'] = [];
        resultOne['2Hact'] = [];resultOne['2Hnact'] = [];
        resultOne['1Hkey'] = [];resultOne['2Hkey'] = [];
        //console.log(result)

        for(let key of Object.keys(result)) {
            //console.log(b.constructor)
            //result[b['matchPeroid']].push(b);
            let match = result[key];let x=1;
            for (let a of match.tags){
                for(let key of Object.keys(a)){
                    console.log('key:',key)
                }
                if(a.id==302){x=0;}
                else{continue;}                   //1,0赋值keypass
            }
            match.x=x;//keypass
            //console.log(match)
            if(match.matchPeriod=='1H'&&match.eventResults=='Won'&&match.x==1){
                resultOne['1Hact'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Accurate'&&match.x==1){
                resultOne['1Hact'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Lost'&&match.x==1){
                resultOne['1Hnact'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Not accurate'&&match.x==1){
                resultOne['1Hnact'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='Neutral'&&match.x==1){
                resultOne['1Hnact'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.eventResults=='none'&&match.x==1){
                resultOne['1Hnact'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Won'&&match.x==1){
                resultOne['2Hact'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Accurate'&&match.x==1){
                resultOne['2Hact'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Lost'&&match.x==1){
                resultOne['2Hnact'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Not accurate'&&match.x==1){
                resultOne['2Hnact'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='Neutral'&&match.x==1){
                resultOne['2Hnact'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.eventResults=='none'&&match.x==1){
                resultOne['2Hnact'].push(match);
            }
            else if(match.matchPeriod=='1H'&&match.x==0){
                resultOne['1Hkey'].push(match);
            }
            else if(match.matchPeriod=='2H'&&match.x==0){
                resultOne['2Hkey'].push(match);
            }
            else {console.log('error');}
        }
        //console.log(resultOne);
        let actions = {}
        actions['firstHalfact'] = []
        actions['firstHalfnact']= []
        actions['secondHalfact'] = []
        actions['secondHalfnact'] = []
        actions['firstHalfkey'] = []
        actions['secondHalfkey'] = []

        for(let key of Object.keys(resultOne)){
            //console.log('key:',key);
            if(key=='1Hact'){
                for(let item of resultOne[key]){
                    let obj = {}
                    //obj.subEventName = item.subEventName
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    obj.x2 = item.endX
                    obj.y2 = item.endY
                    actions['firstHalfact'].push(obj);
                }
            }
            if(key=='1Hnact'){
                for(let item of resultOne[key]){
                    let obj = {}
                    //obj.subEventName = item.subEventName
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    obj.x2 = item.endX
                    obj.y2 = item.endY
                    actions['firstHalfnact'].push(obj);
                }
            }
            if(key=='2Hact'){
                for(let item of resultOne[key]){
                    let obj = {}
                    //obj.subEventName = item.subEventName
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    obj.x2 = item.endX
                    obj.y2 = item.endY
                    actions['secondHalfact'].push(obj);
                }
            }
            if(key=='2Hnact'){
                for(let item of resultOne[key]){
                    let obj = {}
                    //obj.subEventName = item.subEventName
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    obj.x2 = item.endX
                    obj.y2 = item.endY
                    actions['secondHalfnact'].push(obj);
                }
            }
            if(key=='1Hkey'){
                for(let item of resultOne[key]){
                    let obj = {}
                    //obj.subEventName = item.subEventName
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    obj.x2 = item.endX
                    obj.y2 = item.endY
                    actions['firstHalfkey'].push(obj);
                }
            }
            if(key=='2Hkey'){
                for(let item of resultOne[key]){
                    let obj = {}
                    //obj.subEventName = item.subEventName
                    obj.x1 = item.startX
                    obj.y1 = item.startY
                    obj.x2 = item.endX
                    obj.y2 = item.endY
                    actions['secondHalfkey'].push(obj);
                }
            }
        }
        
        ctx.body=actions
        //console.log(result)*/
        /**for(let round of r) {
            console.log(round.constructor)
            for(let key of Object.keys(round)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(round[key] == matchId){
                    //for(let d of round) { bisai.push(d)}
                    bisai.push(round)
                    console.log(bisai)
                }
                else { continue;}
            }
        }
        for(let a of bisai) {
            //console.log(a.constructor)
            for(let key of Object.keys(a)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(a[key] == 'Pass'){
                    //for(let d of round) { bisai.push(d)}
                    result.push(a)
                    console.log(result)
                }
                else { continue;}
            }
        }*/
        /**let resultOne={};
        resultOne['1H']=[];resultOne['2H']=[];
        //console.log(result)

        for(let key of Object.keys(result)) {
            //console.log(b.constructor)
            //result[b['matchPeroid']].push(b);
            let match = result[key]
            switch(match.matchPeriod) {
                case '1H':
                    resultOne['1H'].push(match);
                    //console.log(result)
                    break;
                case '2H':
                    resultOne['2H'].push(match);
                    //console.log(result)
                    break;
                default:
                    console.log('error')
            }
        //delete b;
            

                //else { continue;}
        //console.log(resultOne)
        }
        //console.log(result)
        ctx.body=resultOne*/
        //console.log("a",ctx.body)
        /**ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);*/
    })

/**
 * @swagger
 * paths:
 *   /players/{playerid}/events/duel:
 *     parameters:
 *       - in: path
 *         name: playerid
 *         schema:
 *           type: string
 *         required: true
 *         description: The player ID.
 *     get:
 *       summary: Return the list of the given matches' duel events of the given player
 *       description: ""
 *       matchParam:
 *         - in: query
 *           name: matchId 
 *           description: ""
 *           required: true
 *           type: string
 *       
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */    
    .get('/:playerid/events/duel', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const {matchId} = ctx.query;
        // console.log(playerid, matchId, eventId)
        //const r = await eventCtl.retrieve(playerid);
        //const r = await eventCtl.find({playerId:playerid, eventId, matchId});
        // console.log(r)
        const result = await eventCtl.duelStats(matchId,playerid);           //聚合返回值
        //console.log(result)
        let won_total = 0
        let lost_total = 0
        let all_total = 0
        let neutral_total = 0                                                  //累加ge player对应单元格de值
        for(let key of Object.keys(result)) {
            //console.log('key:', key)
            let a = result[key]
            won_total = won_total+a.wons  
            lost_total = lost_total+a.losts
            all_total = all_total+a.totals
            neutral_total = neutral_total+a.neutrals                                  //遍历累加
            const player = await playerCtl.retrieve(a.playerId)
            //console.log(player)
            a.name = player.shortName;
            a.number = player.countryNumber;
        }
        //console.log(won_total)
        let total = {}
        total.won_total = won_total
        total.lost_total=lost_total
        total.all_total=all_total
        total.neutral_total=neutral_total
        result.total = total                                    //对象添加
        /**let againstArray = [];

        r.map(
            element => {
                // console.log(element)   
                // console.log(element.duelAgainst)
                againstArray.push(element.duelAgainst)
            }
        )

        //let bisai = [];
        let result = [];
        for(let d of r) { result.push(d)}
        var dataSchema = mongoose.Schema({
            eventId:     { type: String },
            eventName:   { type: String },
            matchId: {type: String},
            playerId: {type: String},
            teamId: {type: String},
            duelAgainst: {type: String},
        });
        var dataItem = mongoose.model('result',dataSchema);
        //console.log(result)
        const data = dataItem.aggregate([
            {
                $group:{
                    _id:'$duelAgainst',
                    count:{$sum:1}
                }
            }
        ])
        /**for(let round of r) {
            console.log(round.constructor)
            for(let key of Object.keys(round)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(round[key] == matchId){
                    //for(let d of round) { bisai.push(d)}
                    bisai.push(round)
                    console.log(bisai)
                }
                else { continue;}
            }
        }
        for(let a of bisai) {
            //console.log(a.constructor)
            for(let key of Object.keys(a)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(a[key] == 'Pass'){
                    //for(let d of round) { bisai.push(d)}
                    result.push(a)
                    console.log(result)
                }
                else { continue;}
            }
        }*/
        ctx.body = result
        /**ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);*/
    })

/**
 * @swagger
 * paths:
 *   /players/{playerid}/events/distribution:
 *     parameters:
 *       - in: path
 *         name: playerid
 *         schema:
 *           type: string
 *         required: true
 *         description: The player ID.
 *     get:
 *       summary: Return the list of the given matches' pass events of the given player
 *       description: ""
 *       matchParam:
 *         - in: query
 *           name: matchId 
 *           description: ""
 *           required: true
 *           type: string
 *       
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:playerid/events/distribution', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const {matchId} = ctx.query;
        // console.log(playerid, matchId, eventId)
        //const r = await eventCtl.retrieve(playerid);
        //const r = await eventCtl.find({playerId:playerid, eventId, matchId});
        // console.log(r)
        const result = await eventCtl.passStats(matchId,playerid);          //求平均坐标
        const matchstate = await matchCtl.retrieve(matchId)
        //console.log(matchstate)
        let matchOne = []
        for(let key of Object.keys(matchstate.teamsData)) {
            //if(Number.isNaN(+key)) { continue; }
            //console.log('key:', key);
            let a = matchstate.teamsData[key]
            for (let teamkey of Object.keys(a.formation)){
                //console.log('key:', teamkey);
                let fmt = a.formation[teamkey]
                if (teamkey=='substitutions'){
                    for (let sub of fmt){
                        //console.log(sub)
                        matchOne.push(sub)
                    }
                }
            } 
        }//遍历取替换上下场的球员Id，按对象放入新的数组
        //console.log(matchOne)
        let from_total = 0
        let to_total = 0
        let all_total = 0
        for(let key of Object.keys(result)) {//累加passfrom和passto
            //console.log('key:', key)
            let a = result[key];
            let totals = 0;
            totals = a.froms + a.tos  
            a.totals = totals
            from_total+=a.froms
            to_total+=a.tos
            all_total+=a.totals
            //a.avgX = (a.fxg+a.txg)/2;
            //a.avgY = (a.fyg+a.tyg)/2;
            //delete a.fxg; delete a.txg; delete a.fyg; delete a.tyg;
            const player = await playerCtl.retrieve(a.playerId)               //根据playerId找players表
            //console.log(player)
            a.name = player.shortName;                                        //对象添加palyername and countrynumber
            a.number = player.countryNumber;
            
            //console.log('in')
        }
        //console.log(won_total)
        //let avgx=x/i; let avgy=y/i;                                 
        //console.log(result);
        for (let key of Object.keys(result)) {
            let playersub = result[key]
            playersub.sub = 'lineup';
            for (let a of matchOne){
                //console.log(a)
                if (playersub.playerId == a.playerIn){
                    playersub.sub = 'subIn';
                    playersub.subtime = a.minute;
                }
                else if (playersub.playerId == a.playerOut){
                    playersub.sub = 'subOut';
                    playersub.subtime = a.minute;
                }
            }
        }//将传球对象的数组和上下场球员的数组遍历，一一比对，相同的Id对象加上上下场键值对
        for (let key of Object.keys(result)) {
            let playerpt = result[key];
            const playerpass = await eventCtl.find({playerId:playerpt.playerId, matchId});//, eventId:8});
            //console.log(playerpass)
            let avgx = 0; let avgy = 0; let i = 0
            for (let a of playerpass){
                if (a.passTo == playerid){
                    avgx+=a.startX;
                    avgy+=a.startY;
                    i++;
                }
                else {continue;}
            }
            if (avgx == 0 && avgy == 0){
                playerpt.avgX = 0;
                playerpt.avgY = 0;
            }
            else {
                playerpt.avgX = avgx/i;
                playerpt.avgY = avgy/i;
            }
        }//计算传球给playerid对应球员的球员的平均坐标，平均坐标都等于0表示这个球员没有传球给playerid
        let resultOne = {}
        var res2 = Object.keys(result).sort(function(a,b){ return result[b]["totals"]-result[a]["totals"]; });//字典排序从大到小
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultOne[res2[key]] = result[res2[key]]
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        //console.log(resultOne);
        let total = {}
        total.from_total = from_total
        total.to_total = to_total
        total.all_total = all_total
        resultOne.total = total
        let xplayer = {}
        const player = await playerCtl.retrieve(playerid)
        xplayer.name = player.shortName;
        xplayer.number = player.countryNumber;
        const playerevent = await eventCtl.find({playerId:playerid, eventId:8, matchId});
        //console.log(playerevent)
        let x = 0; let y = 0; let i = 0;
        for (let a of playerevent){
            x+=a.startX;
            y+=a.startY;
            i=i+1;
        }
        //let avgx=x/i; let avgy=y/i;
        xplayer.avgX = x/i;
        xplayer.avgY = y/i;
        xplayer.playerId = playerid;
        resultOne.xplayer = xplayer//对象添加原palyername and countrynumber    
        /**let againstArray = [];

        r.map(
            element => {
                // console.log(element)   
                // console.log(element.duelAgainst)
                againstArray.push(element.duelAgainst)
            }
        )

        //let bisai = [];
        let result = [];
        for(let d of r) { result.push(d)}
        var dataSchema = mongoose.Schema({
            eventId:     { type: String },
            eventName:   { type: String },
            matchId: {type: String},
            playerId: {type: String},
            teamId: {type: String},
            duelAgainst: {type: String},
        });
        var dataItem = mongoose.model('result',dataSchema);
        //console.log(result)
        const data = dataItem.aggregate([
            {
                $group:{
                    _id:'$duelAgainst',
                    count:{$sum:1}
                }
            }
        ])
        /**for(let round of r) {
            console.log(round.constructor)
            for(let key of Object.keys(round)) {
                console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(round[key] == matchId){
                    //for(let d of round) { bisai.push(d)}
                    bisai.push(round)
                    console.log(bisai)
                }
                else { continue;}
            }
        }
        for(let a of bisai) {
            //console.log(a.constructor)
            for(let key of Object.keys(a)) {
                //console.log('key:', key)
                //if(Number.isNaN(+key)) { continue; }
                //console.log('in')
                if(a[key] == 'Pass'){
                    //for(let d of round) { bisai.push(d)}
                    result.push(a)
                    console.log(result)
                }
                else { continue;}
            }
        }*/
        ctx.body = resultOne
        /**ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);*/
    })

    .get('/rate/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const player = await playerCtl.retrieve(playerid)
        const team = await teamCtl.retrieve(player.currentNationalTeamId)
        const club = await teamCtl.retrieve(player.currentTeamId)
        //console.log(team)
        for (let a of team){
            player.countryTeamName = a.name
        }
        for (let b of club){
            player.currentTeamName = b.name
        }
        const fea = await plyfeaCtl.retrieve(playerid);
        let rating = [];
        let a = {}
        a.rate = fea.rate.toFixed(1);
        rating.push(a);
        let b = {}
        b.shot_rate = fea.shot_rate.toFixed(1);
        rating.push(b);
        let c = {}
        c.pass_rate = fea.pass_rate.toFixed(1);
        rating.push(c);
        let d = {}
        d.defending_rate = fea.defending_rate.toFixed(1);
        rating.push(d);
        let e = {}
        e.skill_rate = fea.skill_rate.toFixed(1);
        rating.push(e);
        player.rating = rating
        //player.rate = fea.rate.toFixed(1);
        //player.shot_rate = fea.shot_rate.toFixed(1);
        //player.pass_rate = fea.pass_rate.toFixed(1);
        //player.defending_rate = fea.defending_rate.toFixed(1);
        //player.skill_rate = fea.skill_rate.toFixed(1);
        let eventArea = [];
        for (let a of fea.eventArea){
            let ojbk = {};
            ojbk.X = a.X;
            ojbk.Y = a.Y;
            ojbk.Count = a.Count;
            eventArea.push(ojbk);
        }
        //console.log(eventArea)
        player.eventArea = eventArea;
        ctx.body = player
    })

    .get('/featuretables/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const fea = await plyfeaCtl.retrieve(playerid);
        //console.log(fea)
        let result = {};let informations = {}
        const player = await playerCtl.retrieve(fea.playerId)
        //console.log(player)
        result.playerId = playerid
        result.playername = player.shortName
        const pteam = await teamCtl.retrieve(fea.teamId)
        for (let a of pteam){
            informations.countryTeamName = a.name;
            informations.countryTeamImg = a.countryImg
        }
        informations['Minutes played'] = parseInt(fea.timePlayed);
        informations.Appearances = fea.firstShow + fea.subIn;
        informations['Starting lineup'] = fea.firstShow;
        informations['Yellow cards'] = fea['Yellow Card'];
        informations['Red cards'] = fea['Red Card'];
        const competition = await cmptCtl.retrieve(fea.competitionId);
        informations.competitionName = competition.name
        informations.competitionLogo = competition.logo
        result.informations = informations
        let goal = [];let assist = [];let shot = [];let pass = [];let shotassist = [];let cross = [];let offduel = [];let dribble = [];
        let secass = [];let rpass = [];let rlpass = [];let tpa = [];let pr = [];let pp = [];let rft = []
        const features = await plyfeaCtl.list()
        //console.log(features)
        for (let a of features){
            let ap = parseFloat(a.firstShow + a.subIn);
            if (a.timePlayed > 0 && ap != 0){
                let at = parseInt(a.timePlayed/ap);
                let b = {
                    data:{
                        'Avg.time':at,
                        'Total':a['Shots All Match'],
                        'Avg.per act':(a['Shots All Match']/ap).toFixed(2),
                        'xG/Shot':0
                    }
                }; 
                b.playerId = a.playerId;
                b.Total = a['Shots All Match'];
                //b.data['Total'] = a['Shots All Match'];
                //b['Avg.per 90'] = a['Shots All Match']/a.timePlayed*90;
                //b['Avg.per 90'] = b['Avg.per 90'].toFixed(2)
                //b['Accuracy(%)'] = a['Shots All Accuracy Rate'];
                shot.push(b)
                let c = {
                    data:{
                        'Avg.time':at,
                        'Avg.per act':(a['Shot Assist']/ap).toFixed(2),
                    }
                }
                c.playerId = a.playerId;
                //c.Total = a['Shot Assist'];
                c['Avg.per act'] = a['Shot Assist']/ap;
                c['Avg.per act'] = c['Avg.per act'].toFixed(2)
                shotassist.push(c)
                let d = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Shots All Match'],
                        'Avg.per act':(a['Passes All Match']/ap).toFixed(2),
                        'Accuracy(%)':a['Passes All Accuracy Rate']
                    }
                }
                d.playerId = a.playerId;
                //d.Total = a['Passes All Match'];
                d['Avg.per act'] = a['Passes All Match']/ap;
                d['Avg.per act'] = d['Avg.per act'].toFixed(2);
                //d['Accuracy(%)'] = a['Passes All Accuracy Rate'];
                pass.push(d)
                let e = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Shots All Match'],
                        'Avg.per act':(a['Crosses All Match']/ap).toFixed(2),
                        'Accuracy(%)':a['Crosses All Accuracy Rate']
                    }
                }
                e.playerId = a.playerId;
                //e.Total = a['Crosses All Match'];
                e['Avg.per act'] = a['Crosses All Match']/ap;
                e['Avg.per act'] = e['Avg.per act'].toFixed(2);
                //e['Accuracy(%)'] = a['Crosses All Accuracy Rate'];
                cross.push(e)
                let f = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Shots All Match'],
                        'Avg.per act':(a['Offensive duels All Match']/ap).toFixed(2),
                        'Success(%)':a['Offensive duels All Accuracy Rate']
                    }
                }
                f.playerId = a.playerId;
                //f.Total = a['Offensive duels All Match'];
                f['Avg.per act'] = a['Offensive duels All Match']/ap;
                f['Avg.per act'] = parseFloat(f['Avg.per act'].toFixed(2));
                //f['Success(%)'] = a['Offensive duels All Accuracy Rate'];
                offduel.push(f)
                let g = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Shots All Match'],
                        'Avg.per act':(a['Dribbles All Match']/ap).toFixed(2),
                        'Success(%)':a['Dribbles All Accuracy Rate']
                    }
                }
                g.playerId = a.playerId;
                //g.Total = a['Dribbles All Match'];
                g['Avg.per act'] = a['Dribbles All Match']/ap;
                g['Avg.per act'] = g['Avg.per act'].toFixed(2);
                //g['Success(%)'] = a['Dribbles All Accuracy Rate'];
                dribble.push(g)
                let h = {
                    data:{
                        'Avg.time':at,
                        'Total':a['Goals All Match'],
                        'Avg.per act':(a['Goals All Match']/ap).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        'xG':0
                    }
                }
                h.playerId = a.playerId;
                h.Total = a['Goals All Match'];
                //h['Avg.per 90'] = a['Goals All Match']/a.timePlayed*90;
                //h['Avg.per 90'] = h['Avg.per 90'].toFixed(2);
                //h['Accuracy(%)'] = a['Goals All Accuracy Rate'];
                goal.push(h)
                let i = {
                    data:{
                        'Avg.time':at,
                        'Total':a['Assists'],
                        'Avg.per act':(a['Assists']/ap).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        'xA':0
                    }
                }
                i.playerId = a.playerId;
                i.Total = a['Assists'];
                //i['Avg.per 90'] = a['Assists']/a.timePlayed*90;
                //i['Avg.per 90'] = i['Avg.per 90'].toFixed(2);
                assist.push(i)
                let j = {
                    data:{
                        'Avg.time':at,
                        'Total':a['Second Assist'],
                        //'Avg.per 90':(a['Assists']/a.timePlayed*90).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        'Third assists':a['Third Assist']
                    }
                }
                j.playerId = a.playerId;
                j.Total = a['Second Assist'];
                //j['Third assists'] = a['Third Assist']
                secass.push(j)
                let k = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Second Assist'],
                        'Avg.per act':(a['Received Passes All Match']/ap).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        //'Third assists':a['Third Assist']
                    }
                }
                k.playerId = a.playerId;
                //k.Total = a['Received Passes All Match'];
                k['Avg.per act'] = a['Received Passes All Match']/ap;
                k['Avg.per act'] = k['Avg.per act'].toFixed(2);
                rpass.push(k)
                let l = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Second Assist'],
                        'Avg.per act':(a['Received long passes']/ap).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        //'Third assists':a['Third Assist']
                    }
                }
                l.playerId = a.playerId;
                //l.Total = a['Received long passes'];
                l['Avg.per act'] = a['Received long passes']/ap;
                l['Avg.per act'] = l['Avg.per act'].toFixed(2);
                rlpass.push(l)
                let m = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Second Assist'],
                        'Avg.per act':(a['Touches in Penalty Area All Match']/ap).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        //'Third assists':a['Third Assist']
                    }
                }
                m.playerId = a.playerId;
                //m.Total = a['Touches in Penalty Area All Match'];
                m['Avg.per act'] = a['Touches in Penalty Area All Match']/ap;
                m['Avg.per act'] = m['Avg.per act'].toFixed(2);
                tpa.push(m)
                let n = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Second Assist'],
                        'Avg.per act':(a['Progressive Runs']/ap).toFixed(2),
                        'Avg.runs(m)':(a['Progressive Runs Distance']).toFixed(2)
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        //'Third assists':a['Third Assist']
                    }
                }
                n.playerId = a.playerId;
                //m.Total = a['Touches in Penalty Area All Match'];
                n['Avg.per act'] = (a['Progressive Runs']/ap).toFixed(2);
                pr.push(n)
                let o = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Second Assist'],
                        'Avg.per act':(a['Progressive Passes']/ap).toFixed(2),
                        'Avg.passes(m)':a['Progressive Passes Distance'].toFixed(2)
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        //'Third assists':a['Third Assist']
                    }
                }
                o.playerId = a.playerId;
                //m.Total = a['Touches in Penalty Area All Match'];
                o['Avg.per act'] = (a['Progressive Passes']/ap).toFixed(2);
                pp.push(o)
                let p = {
                    data:{
                        'Avg.time':at,
                        //'Total':a['Second Assist'],
                        'Avg.per act':(a['Recoveries in final third']/ap).toFixed(2),
                        //'Success(%)':a['Dribbles All Accuracy Rate']
                        //'Third assists':a['Third Assist']
                    }
                }
                p.playerId = a.playerId;
                //m.Total = a['Touches in Penalty Area All Match'];
                p['Avg.per act'] = a['Recoveries in final third']/ap;
                p['Avg.per act'] = p['Avg.per act'].toFixed(2);
                rft.push(p)
            }
            else {continue;}
        }
        //console.log(shot)
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        var objectArraySort = function (keyname) {
            return function (objectN, objectM){
                var valueN = objectN[keyname]
                var valueM = objectM[keyname]
                if (valueN < valueM) return 1
                else if  (valueN > valueM) return -1
                else return 0
            }
        }
        shot = shot.sort(compare('Total'))
        shotassist = shotassist.sort(compare('Avg.per act'))
        pass = pass.sort(compare('Avg.per act'))
        cross = cross.sort(compare('Avg.per act'))
        offduel = offduel.sort(objectArraySort('Avg.per act'))
        dribble = dribble.sort(compare('Avg.per act'))
        goal = goal.sort(compare('Total'))
        assist = assist.sort(compare('Total'))
        secass = secass.sort(compare('Total'))
        rpass = rpass.sort(compare('Avg.per act'))
        rlpass = rlpass.sort(compare('Avg.per act'))
        tpa = tpa.sort(compare('Avg.per act'))
        //offduel = offduel.sort(compare('Avg.per act'))
        pr = pr.sort(compare('Avg.per act'))
        pp = pp.sort(compare('Avg.per act'))
        rft = rft.sort(compare('Avg.per act'))
        let i = 0; let shots = {}; let assists = {}; let shotassists = {}; let passes = {}; let crosses = {}; let offduels = {}; let dribbles = {}; let goals = {};
        let secasses = {}; let rpasses = {}; let rlpasses = {}; let tpas = {}; let prs = {}; let pps = {}; let rfts = {}
        for (let a of shot){
            i++;
            a.rank = i;
        }
        let i1 = 0;
        for (let a of shotassist){
            i1++;
            a.rank = i1;
        }
        let i2 = 0;
        for (let a of pass){
            i2++;
            a.rank = i2;
        }
        let i3 = 0;
        for (let a of cross){
            i3++;
            a.rank = i3;
        }
        let i4 = 0;
        for (let a of offduel){
            i4++;
            a.rank = i4;
        }
        let i5 = 0;
        for (let a of dribble){
            i5++;
            a.rank = i5;
        }
        let i6 = 0;
        for (let a of goal){
            i6++;
            a.rank = i6;
        }
        let i7 = 0;
        for (let a of assist){
            i7++;
            a.rank = i7;
        }
        let i8 = 0;
        for (let a of secass){
            i8++;
            a.rank = i8;
        }
        let i9 = 0;
        for (let a of rpass){
            i9++;
            a.rank = i9;
        }
        let i10 = 0;
        for (let a of rlpass){
            i10++;
            a.rank = i10;
        }
        let i11 = 0;
        for (let a of tpa){
            i11++;
            a.rank = i11;
        }
        let i12 = 0;
        for (let a of pr){
            i12++;
            a.rank = i12;
        }
        let i13 = 0;
        for (let a of pp){
            i13++;
            a.rank = i13;
        }
        let i14 = 0;
        for (let a of rft){
            i14++;
            a.rank = i14;
        }
        //console.log(offduel)
        //console.log(shot)
        //console.log(shotassit)
        //console.log(goal)
        for (let b of shot){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of shot){
                        if(c.rank <=8){shots[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of shot){
                        if(c.rank == 1){shots[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){shots[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of shotassist){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of shotassist){
                        if(c.rank <=8){shotassists[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of shotassist){
                        if(c.rank == 1){shotassists[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){shotassists[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of pass){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of pass){
                        if(c.rank <=8){passes[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of pass){
                        if(c.rank == 1){passes[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){passes[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of cross){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of cross){
                        if(c.rank <=8){crosses[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of cross){
                        if(c.rank == 1){crosses[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){crosses[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of offduel){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of offduel){
                        if(c.rank <=8){offduels[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of offduel){
                        if(c.rank == 1){offduels[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){offduels[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of dribble){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of dribble){
                        if(c.rank <=8){dribbles[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of dribble){
                        if(c.rank == 1){dribbles[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){dribbles[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of goal){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of goal){
                        if(c.rank <=8){goals[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of goal){
                        if(c.rank == 1){goals[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){goals[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of assist){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of assist){
                        if(c.rank <=8){assists[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of assist){
                        if(c.rank == 1){assists[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){assists[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of secass){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of secass){
                        if(c.rank <=8){secasses[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of secass){
                        if(c.rank == 1){secasses[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){secasses[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of rpass){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of rpass){
                        if(c.rank <=8){rpasses[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of rpass){
                        if(c.rank == 1){rpasses[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){rpasses[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of rlpass){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of rlpass){
                        if(c.rank <=8){rlpasses[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of rlpass){
                        if(c.rank == 1){rlpasses[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){rlpasses[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of tpa){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of tpa){
                        if(c.rank <=8){tpas[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of tpa){
                        if(c.rank == 1){tpas[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){tpas[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of pr){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of pr){
                        if(c.rank <=8){prs[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of pr){
                        if(c.rank == 1){prs[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){prs[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of pp){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of pp){
                        if(c.rank <=8){pps[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of pp){
                        if(c.rank == 1){pps[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){pps[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let b of rft){
            if (b.playerId == playerid){
                if (b.rank <= 5){
                    for(let c of rft){
                        if(c.rank <=8){rfts[c.playerId]=c;}
                        else {continue;}
                    }
                }
                else {
                    for(let c of rft){
                        if(c.rank == 1){rfts[c.playerId]=c;}
                        else if (c.rank >= b.rank-3 && c.rank <= b.rank+3){rfts[c.playerId]=c;}
                        else {continue;}
                    }
                }
            }
            else{continue;}
        }
        for (let key of Object.keys(shots)){
            let player = shots[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(shotassists)){
            let player = shotassists[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(passes)){
            let player = passes[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(crosses)){
            let player = crosses[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(offduels)){
            let player = offduels[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(dribbles)){
            let player = dribbles[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(goals)){
            let player = goals[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(assists)){
            let player = assists[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(secasses)){
            let player = secasses[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(rpasses)){
            let player = rpasses[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(rlpasses)){
            let player = rlpasses[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(tpas)){
            let player = tpas[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(prs)){
            let player = prs[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(pps)){
            let player = pps[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        for (let key of Object.keys(rfts)){
            let player = rfts[key]
            const p = await playerCtl.retrieve(player.playerId)
            player.name = p.shortName
            const t = await teamCtl.retrieve(p.currentNationalTeamId)
            for (let a of t){
                player.countryTeamName = a.name
            }
        }
        result.Goals = goals
        result.Assists = assists
        result.Shots = shots
        result.Passes = passes
        result.Crosses = crosses
        result['Shot assists'] = shotassists
        result['Second assists'] = secasses
        result['Touches in penalty area'] = tpas
        result['Received passes'] = rpasses
        result['Received long passes'] = rlpasses
        result['Offensive duels'] = offduels
        result.Dribbles = dribbles
        result['Progressive runs'] = prs
        result['Progressive passes'] = pps
        result['Recoveries in final third'] = rfts
        //console.log(result)
        ctx.body = result
    })

    .get('/actions/shots/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        //const {matchId} = ctx.query;
        //const r = await eventCtl.retrieve(playerid);
        const x = await eventCtl.find({playerId:playerid, eventId:10});
        const y = await eventCtl.find({playerId:playerid, eventId:8});
        const z = await eventCtl.find({playerId:playerid, eventId:9});
        //console.log(x)
        let r = [];
        for (let a of x){
            r.push(a);
        }
        for (let a of y){
            r.push(a);
        }
        for (let a of z){
            r.push(a);
        }
        //console.log(r)
        let result = {};let zuobiao = {};let Goal = [];let Wide = [];Blocked = [];zuobiao['On post'] = [];zuobiao['On goal'] = []
        let position = {}; let Goalposition = []; position['On goal position'] = []; let Wideposition = []; position['On post position'] = [];
        /**let g1 = 0;let g2 = 0;let g3 = 0;let g4 = 0;let g5 = 0;let g6 = 0;let g7 = 0;let g8 = 0;let g9 = 0;
        let og1 = 0;let og2 = 0;let og3 = 0;let og4 = 0;let og5 = 0;let og6 = 0;let og7 = 0;let og8 = 0;let og9 = 0;
        let w1 = 0;let w2 = 0;let w3 = 0;let w4 = 0;let w5 = 0;let w6 = 0;let w7 = 0;
        let p1 = 0;let p2 = 0;let p3 = 0;let p4 = 0;let p5 = 0;let p6 = 0;let p7 = 0;*/
        let ts = 0;let to = 0;let tg = 0;
        let is = 0;let io = 0;let ig = 0;
        let os = 0;let oo = 0;let og = 0;
        let ps = 0;let po = 0;let pg = 0;
        let t1 = 0;let t2 = 0;let t3 = 0;let t4 = 0;let t5 = 0;let t6 = 0;
        let l = 0;let m = 0;let n = 0
        for (let a of r){
            ts++;
            if (a.result_name == 'Goal'){
                tg++;
                let obj = {};
                obj.X = (a.x/105*100).toFixed(2);
                obj.Y = (a.y/68*100).toFixed(2);
                Goal.push(obj);
            }
            else if (a.result_name == 'Off_target'){
                let obj = {};
                obj.X = (a.x/105*100).toFixed(2);
                obj.Y = (a.y/68*100).toFixed(2);
                Wide.push(obj);
            }
            else if (a.result_name == 'Blocked'){
                let obj = {};
                obj.X = (a.x/105*100).toFixed(2);
                obj.Y = (a.y/68*100).toFixed(2);
                Blocked.push(obj);
            }
            else if (a.result_name == 'On_post'){
                let obj = {};
                obj.X = (a.x/105*100).toFixed(2);
                obj.Y = (a.y/68*100).toFixed(2);
                zuobiao['On post'].push(obj);
            }
            else if (a.result_name == 'On_target'){
                to++;
                let obj = {};
                obj.X = (a.x/105*100).toFixed(2);
                obj.Y = (a.y/68*100).toFixed(2);
                zuobiao['On goal'].push(obj);
            }
            if (a.period == 1){
                if (a.time_seconds <= 900){
                    t1++
                }
                else if (a.time_seconds > 900 && a.time_seconds <= 1800){
                    t2++
                }
                else if (a.time_seconds > 1800){
                    t3++
                }
            }
            else {
                if (a.time_seconds >= 2700 && a.time_seconds <= 3600){
                    t4++
                }
                else if (a.time_seconds > 3600 && a.time_seconds <= 4500){
                    t5++
                }
                else if (a.time_seconds > 4500){
                    t6++
                }
            }
            if (a.bodypart_name == 'Left'){
                l++;
            }
            else if (a.bodypart_name == 'Head'){
                m++;
            }
            else if (a.bodypart_name == 'Right'){
                n++;
            }
            if (a.eventId == 8 || a.eventId == 9){
                //if (a.x >= 89 && a.y >= 14 && a.y <= 54){
                if (a.attribute_name == 'In_box'){
                    is++;
                    if (a.result_name == 'On_target'){
                        io++;
                    }
                    else if (a.result_name == 'Goal'){
                        ig++;
                    }
                }
                //else if (a.x < 89 || (a.x >= 89 && (a.y < 14 || a.y > 54))){
                else if (a.attribute_name == 'Out_of_box'){
                    os++;
                    if (a.result_name == 'On_target'){
                        oo++;
                    }
                    else if (a.result_name == 'Goal'){
                        og++;
                    }
                }
            }
            if (a.eventId == 10){
                ps++;
                if (a.result_name == 'On_target'){
                    po++;
                }
                else if (a.result_name == 'Goal'){
                    pg++;
                }
            }
            /**for (let tag of a.tags){
                //console.log('key:',tag)
                if (tag.id == 101 || tag.id == 102){
                    let obj = {};
                    obj.X = a.startX;
                    obj.Y = a.startY;
                    Goal.push(obj);
                    for (let b of a.tags){
                        if (b.id == 1201){
                            g1++;
                            let obj1 = {}
                            obj1.position = 'Goal low center';
                            obj1.x = "48%";
                            obj1.y = "66%";
                            obj1.number = g1;
                            if (g1 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal low center'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1202){
                            g2++;
                            let obj1 = {}
                            obj1.position = 'Goal low right';
                            obj1.x = "73%";
                            obj1.y = "66%";
                            obj1.number = g2;
                            if (g2 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal low right'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1203){
                            g3++;
                            let obj1 = {}
                            obj1.position = 'Goal center';
                            obj1.x = "48%";
                            obj1.y = "50%";
                            obj1.number = g3;
                            if (g3 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal center'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1204){
                            g4++;
                            let obj1 = {}
                            obj1.position = 'Goal center left';
                            obj1.x = "25%";
                            obj1.y = "50%";
                            obj1.number = g4;
                            if (g4 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal center left'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1205){
                            g5++;
                            let obj1 = {}
                            obj1.position = 'Goal low left';
                            obj1.x = "25%";
                            obj1.y = "66%";
                            obj1.number = g5;
                            if (g5 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal low left'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1206){
                            g6++;
                            let obj1 = {}
                            obj1.position = 'Goal center right';
                            obj1.x = "73%";
                            obj1.y = "50%";
                            obj1.number = g6;
                            if (g6 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal center right'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1207){
                            g7++;
                            let obj1 = {}
                            obj1.position = 'Goal high center';
                            obj1.x = "48%";
                            obj1.y = "34%";
                            obj1.number = g7;
                            if (g7 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal high center'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1208){
                            g8++;
                            let obj1 = {}
                            obj1.position = 'Goal high left';
                            obj1.x = "25%";
                            obj1.y = "34%";
                            obj1.number = g8;
                            if (g8 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal high left'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1209){
                            g9++;
                            let obj1 = {}
                            obj1.position = 'Goal high right';
                            obj1.x = "73%";
                            obj1.y = "34%";
                            obj1.number = g9;
                            if (g9 == 1){
                                Goalposition.push(obj1)
                            }
                            else{
                                for (let c of Goalposition){
                                    if (c.position == 'Goal high right'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else {continue;}
                    }
                }
                else if (tag.id == 1801 && a.goalsDescription == 'none' && a.subEventId != 36 && a.subEventId != 32 && a.subEventId != 30 && a.subEventId != 31 && a.subEventId != 34){
                    let obj = {};
                    obj.X = a.startX;
                    obj.Y = a.startY;
                    zuobiao['On goal'].push(obj);
                    for (let b of a.tags){
                        if (b.id == 1201){
                            og1++;
                            let obj1 = {}
                            obj1.position = 'Goal low center';
                            obj1.x = "52%";
                            obj1.y = "66%";
                            obj1.number = og1;
                            if (og1 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal low center'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1202){
                            og2++;
                            let obj1 = {}
                            obj1.position = 'Goal low right';
                            obj1.x = "77%";
                            obj1.y = "66%";
                            obj1.number = og2;
                            if (og2 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal low right'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1203){
                            og3++;
                            let obj1 = {}
                            obj1.position = 'Goal center';
                            obj1.x = "52%";
                            obj1.y = "50%";
                            obj1.number = og3;
                            if (og3 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal center'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1204){
                            og4++;
                            let obj1 = {}
                            obj1.position = 'Goal center left';
                            obj1.x = "29%";
                            obj1.y = "50%";
                            obj1.number = og4;
                            if (og4 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal center left'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1205){
                            og5++;
                            let obj1 = {}
                            obj1.position = 'Goal low left';
                            obj1.x = "29%";
                            obj1.y = "66%";
                            obj1.number = og5;
                            if (og5 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal low left'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1206){
                            og6++;
                            let obj1 = {}
                            obj1.position = 'Goal center right';
                            obj1.x = "77%";
                            obj1.y = "50%";
                            obj1.number = og6;
                            if (og6 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal center right'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1207){
                            og7++;
                            let obj1 = {}
                            obj1.position = 'Goal high center';
                            obj1.x = "52%";
                            obj1.y = "34%";
                            obj1.number = og7;
                            if (og7 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal high center'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1208){
                            og8++;
                            let obj1 = {}
                            obj1.position = 'Goal high left';
                            obj1.x = "29%";
                            obj1.y = "34%";
                            obj1.number = og8;
                            if (og8 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal high left'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else if (b.id == 1209){
                            og9++;
                            let obj1 = {}
                            obj1.position = 'Goal high right';
                            obj1.x = "77%";
                            obj1.y = "34%";
                            obj1.number = og9;
                            if (og9 == 1){
                                position['On goal position'].push(obj1)
                            }
                            else{
                                for (let c of position['On goal position']){
                                    if (c.position == 'Goal high right'){
                                        c.number = c.number + 1;
                                    }
                                    else {continue;}
                                }
                            }
                        }
                        else {continue;}
                    }
                }
                else if (tag.id == 2101 && (a.subEventId == 100 || a.subEventId == 33)){
                    let obj = {};
                    obj.X = a.startX;
                    obj.Y = a.startY;
                    Blocked.push(obj);
                }
                else if (tag.id == 1210||tag.id == 1211||tag.id == 1212||tag.id == 1213||tag.id == 1214||tag.id == 1215||tag.id == 1216){
                    let obj = {};
                    obj.X = a.startX;
                    obj.Y = a.startY;
                    Wide.push(obj);
                    if (tag.id == 1210){
                        w1++;
                        let obj1 = {};
                        obj1.position = 'Out low right';
                        obj1.x = "90%";
                        obj1.y = "55%";
                        obj1.number = w1;
                        if (w1 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out low right'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1211){
                        w2++;
                        let obj1 = {};
                        obj1.position = 'Out center left';
                        obj1.x = "2%";
                        obj1.y = "35%";
                        obj1.number = w2;
                        if (w2 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out center left'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1212){
                        w3++;
                        let obj1 = {};
                        obj1.position = 'Out low left';
                        obj1.x = "2%";
                        obj1.y = "55%";
                        obj1.number = w3;
                        if (w3 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out low left'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1213){
                        w4++;
                        let obj1 = {};
                        obj1.position = 'Out center right';
                        obj1.x = "90%";
                        obj1.y = "35%";
                        obj1.number = w4;
                        if (w4 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out center right'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1214){
                        w5++;
                        let obj1 = {};
                        obj1.position = 'Out high center';
                        obj1.x = "45%";
                        obj1.y = "3%";
                        obj1.number = w5;
                        if (w5 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out high center'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1215){
                        w6++;
                        let obj1 = {};
                        obj1.position = 'Out high left';
                        obj1.x = "22%";
                        obj1.y = "3%";
                        obj1.number = w6;
                        if (w6 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out high left'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1216){
                        w7++;
                        let obj1 = {};
                        obj1.position = 'Out high right';
                        obj1.x = "70%";
                        obj1.y = "3%";
                        obj1.number = w7;
                        if (w7 == 1){
                            Wideposition.push(obj1)
                        }
                        else{
                            for (let c of Wideposition){
                                if (c.position == 'Out high right'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else {continue;}  
                }
                else if (tag.id == 1217||tag.id == 1218||tag.id == 1219||tag.id == 1220||tag.id == 1221||tag.id == 1222||tag.id == 1223){
                    let obj = {};
                    obj.X = a.startX;
                    obj.Y = a.startY;
                    zuobiao['On post'].push(obj);
                    if (tag.id == 1217){
                        p1++;
                        let obj1 = {};
                        obj1.position = 'Post low right';
                        obj1.x = "86%";
                        obj1.y = "60%";
                        obj1.number = p1;
                        if (p1 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'Post low right'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1218){
                        p2++;
                        let obj1 = {};
                        obj1.position = 'Post center left';
                        obj1.x = "15%";
                        obj1.y = "40%";
                        obj1.number = p2;
                        if (p2 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'Post center left'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1219){
                        p3++;
                        let obj1 = {};
                        obj1.position = 'Post low left';
                        obj1.x = "15%";
                        obj1.y = "60%";
                        obj1.number = p3;
                        if (p3 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'Post low left'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1220){
                        p4++;
                        let obj1 = {};
                        obj1.position = 'Post center right';
                        obj1.x = "86%";
                        obj1.y = "40%";
                        obj1.number = p4;
                        if (p4 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'Post center right'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1221){
                        p5++;
                        let obj1 = {};
                        obj1.position = 'Post high center';
                        obj1.x = "50%";
                        obj1.y = "21%";
                        obj1.number = p5;
                        if (p5 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'Post high center'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1222){
                        p6++;
                        let obj1 = {};
                        obj1.position = 'Post high left';
                        obj1.x = "27%";
                        obj1.y = "21%";
                        obj1.number = p6;
                        if (p6 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'Post high left'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else if (tag.id == 1216){
                        p7++;
                        let obj1 = {};
                        obj1.position = 'post high right';
                        obj1.x = "75%";
                        obj1.y = "21%";
                        obj1.number = p7;
                        if (p7 == 1){
                            position['On post position'].push(obj1)
                        }
                        else{
                            for (let c of position['On post position']){
                                if (c.position == 'post high right'){
                                    c.number = c.number + 1;
                                }
                                else {continue;}
                            }
                        }
                    }
                    else {continue;}
                }
                else {continue;}
            }*/
        }
        zuobiao.Goal = Goal; zuobiao.Wide = Wide; zuobiao.Blocked = Blocked;
        position.Goalposition = Goalposition; position.Wideposition = Wideposition;
        let shotsTypes = []
        let obj1 = {}; let obj2 = {}; let obj3 = {};
        obj1.type = 'Left foot shots'; obj1.shotsTimes = l; shotsTypes.push(obj1)//; body['Left foot shots'] = leftfoot;
        obj2.type = 'Head shots'; obj2.shotsTimes = n; shotsTypes.push(obj2)//; body['Head shots'] = head;
        obj3.type = 'Right foot shots'; obj3.shotsTimes = m; shotsTypes.push(obj3)//; body['Right foot shots'] = rightfoot;
        let shotsPeriod = []; let obj4 = {}; let obj5 = {}; let obj6 = {}; let obj7 = {}; let obj8 = {}; let obj9 = {};
        const t = await plyfeaCtl.retrieve(playerid);
        obj4.type = "1-15'"; obj4.shotsTimes = t1; shotsPeriod.push(obj4);
        obj5.type = "16-30'"; obj5.shotsTimes = t2; shotsPeriod.push(obj5);
        obj6.type = "31-45+"; obj6.shotsTimes = t3; shotsPeriod.push(obj6);
        obj7.type = "46-60'"; obj7.shotsTimes = t4; shotsPeriod.push(obj7);
        obj8.type = "61-75'"; obj8.shotsTimes = t5; shotsPeriod.push(obj8);
        obj9.type = "76-120+"; obj9.shotsTimes = t6; shotsPeriod.push(obj9);
        let label = []; let obj10 = {}; let obj11 = {}; let obj12 = {}; let obj13 = {}; let obj14 = {}; let obj15 = {};
        obj15.name = 'Total'; obj15.Shots = ts; obj15['on target'] = to; obj15.percent = (to/(ts || 1)*100).toFixed()+'%'; obj15.xG = 0; obj15['Goals'] = tg; obj15['Goal conversion'] = (tg/(ts || 1)*100).toFixed()+'%'; label.push(obj15);
        obj10.name = 'Inside penalty area'; obj10.Shots = is; obj10['on target'] = io; obj10.percent = (io/(is || 1)*100).toFixed()+'%'; obj10.xG = 0; obj10['Goals'] = ig; obj10['Goal conversion'] = (ig/(is || 1)*100).toFixed()+'%'; label.push(obj10);
        obj11.name = 'Outside penalty area'; obj11.Shots = os; obj11['on target'] = oo; obj11.percent = (oo/(os || 1)*100).toFixed()+'%'; obj11.xG = 0; obj11['Goals'] = og; obj11['Goal conversion'] = (og/(os || 1)*100).toFixed()+'%'; label.push(obj11);
        //obj12.name = 'After crosses'; obj12.Shots = t['After Cross']; obj12['on target'] = t['After Cross on target']; obj12.percent = (t['After Cross on target']/(t['After Cross'] || 1)*100).toFixed()+'%'; obj12.xG = 0; obj12['Goals'] = t['After Cross Goals']; obj12['Goal conversion'] = t['After Cross goal conversion']; label.push(obj12);
        //obj13.name = 'After set pieces'; obj13.Shots = t['After set pieces']; obj13['on target'] = t['After set pieces on target']; obj13.percent = (t['After set pieces on target']/(t['After set pieces'] || 1)*100).toFixed()+'%'; obj13.xG = 0; obj13['Goals'] = t['After set pieces Goals']; obj13['Goal conversion'] = t['After set pieces goal conversion']; label.push(obj13);
        obj14.name = 'DFKs and penalties'; obj14.Shots = ps; obj14['on target'] = po; obj14.percent = (po/(ps || 1)*100).toFixed()+'%'; obj14.xG = 0; obj14['Goals'] = pg; obj14['Goal conversion'] = (pg/(ps || 1)*100).toFixed()+'%'; label.push(obj14);
        //obj15.Shots = t['Shots All Match']; obj15['on target'] = t['Shots All Match Accuracy']; obj15.percent = (t['Shots All Match Accuracy']/(t['Shots All Match'] || 1)*100).toFixed()+'%'; obj15.xG = 0; obj15['Goals'] = t['Goals All Match']; obj15['Goal conversion'] = (t['Goals All Match']/t['Shots All Match']*100).toFixed()+'%'; label['Total'] = obj15;
        //console.log(zuobiao)
        result.zuobiao = zuobiao;
        result.shotsPeriod = shotsPeriod;
        result.shotsTypes = shotsTypes;
        result.positions = position
        result.label = label;
        ctx.body = result;
    })

    .get('/actions/xGdistribution/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of r){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj.Goals = parseFloat((a['Goals All Match']/a.timePlayed*90).toFixed(1));
            obj.Shots = parseFloat((a['Shots All Match']/a.timePlayed*90).toFixed(1));
            obj['Touches in Penalty Area'] = parseFloat((a['Touches in Penalty Area All Match']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret1 = {};
        for( let pf of playerfeatures){
            if (pf.Goals != 'none'){
                let Goals = pf.Goals;
                if(!Object.hasOwnProperty.call(ret1, Goals)){//ret无playerId,tui
                    ret1[Goals] = { Goals, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret1[Goals].number = ret1[Goals].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf.Shots != 'none'){
                let Shots = pf.Shots;
                if(!Object.hasOwnProperty.call(ret2, Shots)){//ret无playerId,tui
                    ret2[Shots] = { Shots, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[Shots].number = ret2[Shots].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Touches in Penalty Area'] != 'none'){
                let tpa = pf['Touches in Penalty Area'];
                if(!Object.hasOwnProperty.call(ret3, tpa)){//ret无playerId,tui
                    ret3[tpa] = { tpa, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[tpa].number = ret3[tpa].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultOne = []; let resultTwo = []; let resultThree = [];
        var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[a]["Goals"]-ret1[b]["Goals"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultOne.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["Shots"]-ret2[b]["Shots"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["tpa"]-ret3[b]["tpa"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let result = {};
        result.Goals = resultOne;
        result.Shots = resultTwo;
        result['Touches in Penalty Area'] = resultThree;
        for (let a of r){
            if (a.playerId == playerid){
                result.playerId = a.playerId;
                result.goals = parseFloat((a['Goals All Match']/a.timePlayed*90).toFixed(1));
                result.shots = parseFloat((a['Shots All Match']/a.timePlayed*90).toFixed(1));
                result['touches in Penalty Area'] = parseFloat((a['Touches in Penalty Area All Match']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        //console.log(resultOne);
        ctx.body = result
    })
    .get('/actions/penaltiestaken/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({playerId:playerid, subEventId:35}); 
        let result = {}; let label = [];
        for (let a of r){
            const m = await matchCtl.retrieve(a.matchId);
            for (let key of Object.keys(m.teamsData)){
                let team = m.teamsData[key];
                //console.log(team)
                if (team.teamId != a.teamId){
                    for (let key1 of Object.keys(team.formation)){
                        //console.log('key:',key1)
                        let player = team.formation[key1];
                        if (key1 == 'lineup'){
                            for(let b of player){
                                const p = await playerCtl.retrieve(b.playerId)
                                let position = p.role
                                if (position.name == 'Goalkeeper'){
                                    let obj = {}
                                    obj.Date = (m.dateutc).substring(0,10);
                                    obj.Match = m.label;
                                    obj.Goalkeeper = p.shortName;
                                    obj.Outcome = a.goalsDescription;
                                    label.push(obj);
                                }
                            }
                        }
                        else {continue;}
                    }
                }
                else {continue;}
            }
        }
        //console.log(label)
        let positions = []
        let g1 = 0;let g2 = 0;let g3 = 0;let g4 = 0;let g5 = 0;let g6 = 0;let g7 = 0;let g8 = 0;let g9 = 0;
        let og1 = 0;let og2 = 0;let og3 = 0;let og4 = 0;let og5 = 0;let og6 = 0;let og7 = 0;let og8 = 0;let og9 = 0;
        let b = 0;let c = 0;
        for (let a of r){
            let gTags = a.tags.filter( t=>Math.floor(+t.id/100)===12);
            if(gTags.length == 0) { continue; }
            let tags = a.tags.map(t=>+t.id);
            switch(gTags[0].id) {
                case 1201:
                    if(tags.includes(101)){ b++; } else{ c++;}
                    break;
            }
            /**if(tags.includes(1201)){
                if(tags.includes(101)){
                    g1++;
                }else{
                    (og1-g1) ++;
                }
            }*/ 
            for (let tag of a.tags){
                if (tag.id == 1201){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g1++;
                        }
                        else {continue;}
                    }
                    og1++;
                }
                else if (tag.id == 1202){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g2++;
                        }
                        else {continue;}
                    }
                    og2++;
                }
                else if (tag.id == 1203){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g3++;
                        }
                        else {continue;}
                    }
                    og3++;
                }
                else if (tag.id == 1204){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g4++;
                        }
                    }
                    og4++;
                }
                else if (tag.id == 1205){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g5++;
                        }
                        else {continue;}
                    }
                    og5++;
                }
                else if (tag.id == 1206){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g6++;
                        }
                        else {continue;}
                    }
                    og6++;
                }
                else if (tag.id == 1207){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g7++;
                        }
                        else {continue;}
                    }
                    og7++;
                }
                else if (tag.id == 1208){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g8++;
                        }
                        else {continue;}
                    }
                    og8++;
                }
                else if (tag.id == 1209){
                    for (let b of a.tags){
                        if (b.id == 101){
                            g9++;
                        }
                        else {continue;}
                    }
                    og9++;
                }
                else {continue;}
            }
        }
        //console.log(b);
        //console.log(c)
        //console.log(g2)
        let obj8 = {}; obj8.position = 'highLeft'; obj8.x1 = '20%'; obj8.y1 = '36%'; if(g8!=0){obj8.number = (g8/og8*100).toFixed()+'%'} else {obj8.number = 0+'%'}; obj8.rate = g8+'/'+og8; positions.push(obj8);
        let obj7 = {}; obj7.position = 'highCenter'; obj7.x1 = '50%'; obj7.y1 = '36%'; if(g7!=0){obj7.number = (g7/og7*100).toFixed()+'%'} else {obj7.number = 0+'%'}; obj7.rate = g7+'/'+og7; positions.push(obj7);
        let obj9 = {}; obj9.position = 'highRight'; obj9.x1 = '80%'; obj9.y1 = '36%'; if(g9!=0){obj9.number = (g9/og9*100).toFixed()+'%'} else {obj9.number = 0+'%'}; obj9.rate = g9+'/'+og9; positions.push(obj9);
        let obj4 = {}; obj4.position = 'centerLeft'; obj4.x1 = '20%'; obj4.y1 = '60%'; if(g4!=0){obj4.number = (g4/og4*100).toFixed()+'%'} else {obj4.number = 0+'%'}; obj4.rate = g4+'/'+og4; positions.push(obj4);
        let obj3 = {}; obj3.position = 'Center'; obj3.x1 = '50%'; obj3.y1 = '60%'; if(g3!=0){obj3.number = (g3/og3*100).toFixed()+'%'} else {obj3.number = 0+'%'}; obj3.rate = g3+'/'+og3; positions.push(obj3);
        let obj6 = {}; obj6.position = 'centerRight'; obj6.x1 = '80%'; obj6.y1 = '60%'; if(g6!=0){obj6.number = (g6/og6*100).toFixed()+'%'} else {obj6.number = 0+'%'}; obj6.rate = g6+'/'+og6; positions.push(obj6);
        let obj5 = {}; obj5.position = 'lowLeft'; obj5.x1 = '20%'; obj5.y1 = '84%'; if(g5!=0){obj5.number = (g5/og5*100).toFixed()+'%'}else {obj5.number = 0+'%'}; obj5.rate = g5+'/'+og5; positions.push(obj5);
        let obj1 = {}; obj1.position = 'lowCenter'; obj1.x1 = '50%'; obj1.y1 = '84%'; if(g1!=0) {obj1.number = (g1/og1*100).toFixed()+'%'} else {obj1.number = 0+'%'}; obj1.rate = g1+'/'+og1; positions.push(obj1);
        let obj2 = {}; obj2.position = 'lowRight'; obj2.x1 = '80%'; obj2.y1 = '84%'; if(g2!=0){obj2.number = (g2/og2*100).toFixed()+'%'} else {obj2.number = 0+'%'}; obj2.rate = g2+'/'+og2; positions.push(obj2);
        //let obj3 = {}; obj3.position = 'Goal center'; if(g3!=0){obj3.number = (g3/og3*100).toFixed()+'%'} else {obj3.number = 0};positions.push(obj3);
        //let obj4 = {}; obj4.position = 'Goal center left'; if(g4!=0){obj4.number = (g4/og4*100).toFixed()+'%'} else {obj4.number = 0}; positions.push(obj4);
        //let obj5 = {}; obj5.position = 'Goal low left'; if(g5!=0){obj5.number = (g5/og5*100).toFixed()+'%'}else {obj5.number = 0}; positions.push(obj5);
        //let obj6 = {}; obj6.position = 'Goal center right'; if(g6!=0){obj6.number = (g6/og6*100).toFixed()+'%'} else {obj6.number = 0}; positions.push(obj6);
        //let obj7 = {}; obj7.position = 'Goal high center'; if(g7!=0){obj7.number = (g7/og7*100).toFixed()+'%'} else {obj7.number = 0}; positions.push(obj7);
        //let obj8 = {}; obj8.position = 'Goal high left'; if(g8!=0){obj8.number = (g8/og8*100).toFixed()+'%'} else {obj8.number = 0}; positions.push(obj8);
        //let obj9 = {}; obj9.position = 'Goal high right'; if(g9!=0){obj9.number = (g9/og9*100).toFixed()+'%'} else {obj9.number = 0}; positions.push(obj9);
        result.positions = positions;
        result.label = label;
        ctx.body = result;
    })

    .get('/actions/shotassists/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r1 = await eventCtl.find({playerId:playerid});
        const r3 = await eventCtl.find({eventId:8,playerId:playerid});
        const r4 = await eventCtl.find({eventId:3,playerId:playerid});
        const r5 = await eventCtl.find({eventId:10})
        //console.log(r5)
        let r2 = [];
        for (let a of r4){
            r2.push(a);
        }
        for (let a of r3){
            r2.push(a);
        }
        //console.log(r2)
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        function compare1(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;
            }
        }
        r2 = r2.sort(compare1('eventSec'));
        //r3 = r3.sort(compare1('eventSec'));
        //console.log(r3)
        let result = {}; let zuobiao = {}; zuobiao.Assist = [];
        /**function binary_search(arr, key) {
            var low = 0,
                high = arr.length - 1;
         
            while(low <= high) {
                var mid = parseInt((high + low) /2);
                  // console.log(mid+'h'+high+'l'+low);
                if(key == arr[mid]) {
                    return mid;
                } else if(key > arr[mid]) {
                    low = mid + 1;
                } else {
                    high = mid -1;
                }
            }
            return -1
        }*/
        let ret = {}; let shotassists = []
        for (let a of r5){
            let t = a.eventBeforeTime;
            for (let b of r2){
                if (b.eventSec == t && b.matchId == a.matchId){
                    let playerId = a.playerId; let i = 0;
                    if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                        ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                    }else{//ret有playerId,tui 对应数值
                        ret[playerId]['Shot assists'] = ret[playerId]['Shot assists'] + 1; 
                        //ret[playerId].fxg = fg.fxg;
                        //ret[playerId].fyg = fg.fyg;
                    }
                    for (let tag of b.tags){
                        if (tag.id == 301){
                            i = 1;
                        }
                        else {continue;}
                    }
                    if (i == 0){
                        let obj = {}; let z = 0; 
                        //obj.x = a.startX;
                        //obj.y = a.startY;
                        for(let position of b.positions ){
                            z++;
                            if (z == 1){
                                obj.x1 = position.x;
                                obj.y1 = position.y;
                            }
                            if (z == 2){
                                obj.x2 = position.x;
                                obj.y2 = position.y;
                            }
                        }
                        shotassists.push(obj);
                    }
                    else {
                        if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                            ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                        }else{//ret有playerId,tui 对应数值 
                            ret[playerId].Assists = ret[playerId].Assists + 1;
                            //ret[playerId].fxg = fg.fxg;
                            //ret[playerId].fyg = fg.fyg;
                        }
                    }
                    //console.log(i)
                }
                else if (b.eventSec > t){break;}
                else {continue;}
            }
            /**if (a.eventAfterId == 10){
                for (let b of r5){
                    if (b.eventSec == a.eventAfterTime && b.matchId == a.matchId){
                        let playerId = b.playerId; let i = 0;
                        if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                            ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                        }else{//ret有playerId,tui 对应数值
                            ret[playerId]['Shot assists'] = ret[playerId]['Shot assists'] + 1; 
                            //ret[playerId].fxg = fg.fxg;
                            //ret[playerId].fyg = fg.fyg;
                        }
                        for (let tag of a.tags){
                            if (tag.id == 301){
                                i = 1;
                            }
                            else {continue;}
                        }
                        if (i == 0){
                            let obj = {}; let z = 0; 
                            //obj.x = a.startX;
                            //obj.y = a.startY;
                            for(let position of a.positions ){
                                z++;
                                if (z == 1){
                                    obj.x1 = position.x;
                                    obj.y1 = position.y;
                                }
                                if (z == 2){
                                    obj.x2 = position.x;
                                    obj.y2 = position.y;
                                }
                            }
                            shotassists.push(obj);
                        }
                        else {
                            if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                                ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                            }else{//ret有playerId,tui 对应数值 
                                ret[playerId].Assists = ret[playerId].Assists + 1;
                                //ret[playerId].fxg = fg.fxg;
                                //ret[playerId].fyg = fg.fyg;
                            }
                        }
                    }
                    //else if (b.eventSec > a.eventAfterTime){break;}
                    else {continue;}
                } 
            }
            else {continue;}*/
        }
        for (let a of r1){
            for (let tag of a.tags){
                if (tag.id == 301){
                    let obj = {}; let i = 0; 
                    //obj.x = a.startX;
                    //obj.y = a.startY;
                    for(let position of a.positions ){
                        i++;
                        if (i == 1){
                            obj.x1 = position.x;
                            obj.y1 = position.y;
                        }
                        else if (i == 2){
                            obj.x2 = position.x;
                            obj.y2 = position.y;
                        }
                        else{continue;}
                    }
                    //obj.eventId = a.eventId;
                    //obj.subeventId = a.subEventId;
                    zuobiao.Assist.push(obj);
                    /**const assists = await eventCtl.find({eventSec: a.eventAfterTime, matchId: a.matchId});
                    for (let b of assists){
                        for (let tag1 of b.tags){
                            if (tag1.id == 101){
                                let playerId = b.playerId;
                                if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                                    ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                                }else{//ret有playerId,tui 对应数值 
                                    ret[playerId].Assists = ret[playerId].Assists + 1;
                                    //ret[playerId].fxg = fg.fxg;
                                    //ret[playerId].fyg = fg.fyg;
                                }
                            }
                            else {continue;}
                        }
                    }*/
                }
                else {continue;}
            }
        }
        //console.log(ret)
        zuobiao['Shot assist'] = shotassists; let table = [];
        for (let key of Object.keys(ret)){
            let player = ret[key];
            table.push(player);
        }
        table = table.sort(compare('Assists'));
        //console.log(table)
        let Table = []
        for (let a of table){
            const player = await playerCtl.retrieve(a.playerId)
            //console.log(player)
            obj = {
                Receiver: player.shortName,
                'Shot assists': a['Shot assists'],
                xA: 0,
                Assists: a.Assists
            }
            Table.push(obj);
        }
        //console.log(table)
        result.zuobiao = zuobiao;
        result.table = Table;
        ctx.body = result;
    })

    .get('/actions/xAdistribution/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of r){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj.Assists = parseFloat((a['Assists']/a.timePlayed*90).toFixed(1));
            obj['Shot Assist'] = parseFloat((a['Shot Assist']/a.timePlayed*90).toFixed(1));
            obj['Through passes'] = parseFloat((a['Through passes All Match']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret1 = {};
        for( let pf of playerfeatures){
            if (pf.Assists != 'none'){
                let Assists = pf.Assists;
                if(!Object.hasOwnProperty.call(ret1, Assists)){//ret无playerId,tui
                    ret1[Assists] = { Assists, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret1[Assists].number = ret1[Assists].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Shot Assist'] != 'none'){
                let SA = pf['Shot Assist'];
                if(!Object.hasOwnProperty.call(ret2, SA)){//ret无playerId,tui
                    ret2[SA] = { SA, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[SA].number = ret2[SA].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Through passes'] != 'none'){
                let tp = pf['Through passes'];
                if(!Object.hasOwnProperty.call(ret3, tp)){//ret无playerId,tui
                    ret3[tp] = { tp, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[tp].number = ret3[tp].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultOne = []; let resultTwo = []; let resultThree = [];
        var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[a]["Assists"]-ret1[b]["Assists"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultOne.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["SA"]-ret2[b]["SA"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["tp"]-ret3[b]["tp"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let result = {};
        result.Assists = resultOne;
        result['Shot Assists'] = resultTwo;
        result['Through passes'] = resultThree;
        for (let a of r){
            if (a.playerId == playerid){
                result.playerId = a.playerId;
                result.assists = parseFloat((a['Assists']/a.timePlayed*90).toFixed(1));
                result['shot Assists'] = parseFloat((a['Shot Assist']/a.timePlayed*90).toFixed(1));
                result['through passes'] = parseFloat((a['Through passes All Match']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        //console.log(resultOne);
        ctx.body = result
    })

    .get('/actions/penaltydelivery/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({playerId:playerid})
        //console.log(r)
        let result = {}; let pass = []; let cross = []; let keypass = []; let carry = [];
        lp = 0; lpa = 0; lc = 0; lca = 0; lk = 0; lcr = 0;
        rp = 0; rpa = 0; rc = 0; rca = 0; rk = 0; rcr = 0;
        cp = 0; cpa = 0; cc = 0; cca = 0; ck = 0; ccr = 0;
        for (let a of r){
            let i = 0; //let h = 0; let j = 0; let k = 0;
            if (a.result_name == 'Key_pass'){
                i++;
            }
            if (i == 1 && (a.x < 89 || (a.y < 14 || a.y > 54)) && (a.end_x >= 89 && a.end_y >= 14 && a.end_y <= 54)){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                keypass.push(obj);
                if (a.y < 22.7 && a.y >=0){
                    lk++;
                }
                else if (a.y < 45.4 && a.y >=22.7){
                    ck++;
                }
                else if (a.y <= 68 && a.y >= 45.4){
                    rk++;
                }
            }
            if (i != 1 && (a.eventId == 5 || a.eventId == 6 || a.eventId == 7) && (a.x < 89 || (a.y < 14 || a.y > 54)) && (a.end_x >= 89 && a.end_y >= 14 && a.end_y <= 54)){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                cross.push(obj);
                if (a.y < 22.7 && a.y >=0){
                    lc++;
                    if (a.result_name == 'Successful'){
                        lca++;
                    }
                }
                else if (a.y < 45.4 && a.y >=22.7){
                    cc++;
                    if (a.result_name == 'Successful'){
                        cca++;
                    }
                }
                else if (a.y <= 68 && a.y >= 45.4){
                    rc++;
                    if (a.result_name == 'Successful'){
                        rca++;
                    }
                }
            }
            if (i != 1 && a.eventId == 27 && (a.x < 89 || (a.y < 14 || a.y > 54)) && (a.end_x >= 89 && a.end_y >= 14 && a.end_y <= 54)){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                carry.push(obj);
                if (a.y < 22.7 && a.y >=0){
                    lcr++;
                }
                else if (a.y < 45.4 && a.y >=22.7){
                    ccr++;
                }
                else if (a.y <= 68 && a.y >= 45.4){
                    rcr++;
                }
            }
            if (i != 1 && (a.eventId == 0 || a.eventId == 1 || a.eventId == 4) && (a.x < 89 || (a.y < 14 || a.y > 54)) && (a.end_x >= 89 && a.end_y >= 14 && a.end_y <= 54)){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                pass.push(obj);
                if (a.y < 22.7 && a.y >=0){
                    lp++;
                    if (a.result_name == 'Successful'){
                        lpa++;
                    }
                }
                else if (a.y < 45.4 && a.y >=22.7){
                    cp++;
                    if (a.result_name == 'Successful'){
                        cpa++;
                    }
                }
                else if (a.y <= 68 && a.y >= 45.4){
                    rp++;
                    if (a.result_name == 'Successful'){
                        rpa++;
                    }
                }
            }
            /**for (let tag of a.tags){
                if (tag.id == 302){
                    i++;
                }
                else if (tag.id ==501 || tag.id ==502 || tag.id ==503 || tag.id ==504){
                    h++;
                }
                else if (tag.id == 1801){
                    k++
                }
                else {continue;}
            }
            //console.log(k)
            if (a.subEventId == 80 || a.subEventId == 32 || a.subEventId == 36 || a.subEventId == 30){
                j = 1;
            }
            if (i == 1){
                let z = 0; let obj = {};
                for (let position of a.positions){
                    z++;
                    if(z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y
                    }
                    else {continue}
                }
                if ((obj.x1 <= 85 || (obj.y1 <= 20 || obj.y1 >=80)) && obj.x2 > 85 && obj.y2 < 80 && obj.y2 >20){
                    keypass.push(obj);
                    if (obj.y1 < 33 && obj.y1 >=0){
                        lk++;
                    }
                    else if (obj.y1 <= 66 && obj.y1 >=33){
                        ck++;
                    }
                    else if (obj.y1 <= 100 && obj.y1 >66){
                        rk++;
                    }
                    else {continue;}
                }
                else {continue;}
            }
            else if (i == 0 && h == 1){
                let z = 0; let obj = {};
                for (let position of a.positions){
                    z++;
                    if(z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y
                    }
                    else {continue}
                }
                if ((obj.x1 <= 85 || (obj.y1 <= 20 || obj.y1 >=80)) && obj.x2 > 85 && obj.y2 < 80 && obj.y2 >20){
                    carry.push(obj);
                    if (obj.y1< 33 && obj.y1 >=0){
                        lcr++;
                    }
                    else if (obj.y1 <= 66 && obj.y1 >=33){
                        ccr++;
                    }
                    else if (obj.y1 <= 100 && obj.y1 >66){
                        rcr++;
                    }
                    else {continue;}
                }
                else {continue;}
            }
            else if (i == 0 && h ==0 && j == 1){
                let z = 0; let obj = {};
                for (let position of a.positions){
                    z++;
                    if(z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y
                    }
                    else {continue}
                }
                if ((obj.x1 <= 85 || (obj.y1 <= 20 || obj.y1 >=80)) && obj.x2 > 85 && obj.y2 < 80 && obj.y2 >20){
                    cross.push(obj);
                    if (obj.y1 < 33 && obj.y1 >=0){
                        lc++;
                        if (k == 1){
                            lca++;
                        }
                        else {continue;}
                    }
                    else if (obj.y1 <= 66 && obj.y1 >=33){
                        cc++;
                        if (k == 1){
                            cca++;
                        }
                        else {continue;}
                    }
                    else if (obj.y1 <= 100 && obj.y1 >66){
                        rc++;
                        if (k == 1){
                            rca++;
                        }
                        else {continue;}
                    }
                    else {continue;}
                }
                else {continue;}
            }
            else if (i == 0 && h ==0 && j == 0 && (a.eventId == 8 || a.eventId == 3)){
                let z = 0; let obj = {};
                for (let position of a.positions){
                    z++;
                    if(z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y
                    }
                    else {continue}
                }
                if ((obj.x1 <= 85 || (obj.y1 <= 20 || obj.y1 >=80)) && obj.x2 > 85 && obj.y2 < 80 && obj.y2 >20){
                    pass.push(obj);
                    if (obj.y1 < 33 && obj.y1 >=0){
                        lp++;
                        //for (let tag1 of a.tags){
                            //if (tag1.id == 1801){
                                //lpa++;
                            //}
                            //else {continue;}
                        //}
                        if (k == 1){
                            lpa++;
                        }
                       else {continue;}
                    }
                    else if (obj.y1 <= 66 && obj.y1 >=33){
                        cp++;
                        //for (let tag1 of a.tags){
                            //if (tag1.id == 1801){
                                //cpa++;
                            //}
                            //else {continue;}
                        //}
                        if (k == 1){
                            cpa++;
                        }
                        else {continue;}
                    }
                    else if (obj.y1 <= 100 && obj.y1 >66){
                        rp++;
                        if (k == 1){
                            rpa++;
                        }
                        else {continue;}
                    }
                    else {continue;}
                }
                else {continue;}
            }
            else {continue;}*/
        }
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Passes to penalty area'] = parseFloat((a['Pass to Penalty area All Match']/a.timePlayed*90).toFixed(1));
            obj['Accurate passes to penalty area'] = parseInt(a['Pass to Penalty area All Accuracy Rate']);
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Passes to penalty area'] != 'none'){
                let pp = pf['Passes to penalty area'];
                if(!Object.hasOwnProperty.call(ret2, pp)){//ret无playerId,tui
                    ret2[pp] = { pp, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[pp].number = ret2[pp].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Accurate passes to penalty area'] != 'none'){
                let app = pf['Accurate passes to penalty area'];
                if(!Object.hasOwnProperty.call(ret3, app)){//ret无playerId,tui
                    ret3[app] = { app, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[app].number = ret3[app].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["pp"]-ret2[b]["pp"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["app"]-ret3[b]["app"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        for (let a of resultThree){
            a.app = a.app + '%';
        }
        let figure = {};
        figure['Passes to penalty area'] = resultTwo;
        figure['Accurate passes to penalty area'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['passes to penalty area'] = parseFloat((a['Pass to Penalty area All Match']/a.timePlayed*90).toFixed(1));
                figure['accurate passes to penalty area'] = a['Pass to Penalty area All Accuracy Rate'];
            }
            else {continue;}
        }
        result.Pass = pass; result.Cross = cross; result['Key pass'] = keypass; result.Carry = carry;
        let table = []; let leftf = {}; let center = {}; let rightf = {}; let total = {}
        leftf.name = 'Left flank'; leftf.Passes = lp; leftf.paccurate = lpa; leftf.Passrate = ((lpa/lp || 0)*100).toFixed()+'%'; leftf.Crosses = lc; leftf.caccurate = lca; leftf.crossrate = ((lca/lc || 0)*100).toFixed()+'%'; leftf['Key passes'] = lk; leftf.Carries = lcr; table.push(leftf);
        center.name = 'Center'; center.Passes = cp; center.paccurate = cpa; center.Passrate = ((cpa/cp || 0)*100).toFixed()+'%'; center.Crosses = cc; center.caccurate = cca; center.crossrate = ((cca/cc || 0)*100).toFixed()+'%'; center['Key passes'] = ck; center.Carries = ccr; table.push(center);
        rightf.name = 'Right flank'; rightf.Passes = rp; rightf.paccurate = rpa; rightf.Passrate = ((rpa/rp || 0)*100).toFixed()+'%'; rightf.Crosses = rc; rightf.caccurate = rca; rightf.crossrate = ((rca/rc || 0)*100).toFixed()+'%'; rightf['Key passes'] = rk; rightf.Carries = rcr; table.push(rightf);
        total.name = 'Total'; total.Passes = lp+cp+rp; total.paccurate = lpa+cpa+rpa; total.Passrate = ((total.paccurate/total.Passes || 0)*100).toFixed()+'%'; total.Crosses = lc+cc+rc; total.caccurate = lca+cca+rca; total.crossrate = ((total.caccurate/total.Crosses || 0)*100).toFixed()+'%'; total['Key passes'] = lk+ck+rk; total.Carries = lcr+ccr+rcr; table.push(total);
        result.Figure = figure;
        result.Table = table;
        ctx.body = result;
    })

    .get('/actions/cross/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{eventId:5},{eventId:6},{eventId:7}],playerId:playerid});
        let result = {}; let unsuccessful = []; let successful = []; let Keypass = [];
        let lc = 0, lcs = 0, lg = 0, lgc = 0, la = 0;
        let rc = 0, rcs = 0, rg = 0, rgc = 0, ra = 0;
        for (let a of r){
            let i = 0;
            if (a.result_name == 'Key_pass'){
                i++;
            }
            if (i == 1){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                Keypass.push(obj);
                if (a.y <= 34){
                    lgc++;
                }
                else if (a.y > 34){
                    rgc++;
                }
            }
            if (i != 1){
                if (a.y <= 34){
                    lc++;
                    if (a.result_name != 'Unsuccessful'){
                        lcs++;
                        let obj = {}
                        obj.x1 = (a.x/105*100).toFixed(2);
                        obj.y1 = (a.y/68*100).toFixed(2);
                        obj.x2 = (a.end_x/105*100).toFixed(2);
                        obj.y2 = (a.end_y/68*100).toFixed(2);
                        successful.push(obj);
                    }
                    else if (a.result_name == 'Unsuccessful'){
                        lg++;
                        let obj = {}
                        obj.x1 = (a.x/105*100).toFixed(2);
                        obj.y1 = (a.y/68*100).toFixed(2);
                        unsuccessful.push(obj);
                    }
                }
                if (a.y > 34){
                    rc++;
                    if (a.result_name != 'Unsuccessful'){
                        rcs++;
                        let obj = {}
                        obj.x1 = (a.x/105*100).toFixed(2);
                        obj.y1 = (a.y/68*100).toFixed(2);
                        obj.x2 = (a.end_x/105*100).toFixed(2);
                        obj.y2 = (a.end_y/68*100).toFixed(2);
                        successful.push(obj);
                    }
                    else if (a.result_name == 'Unsuccessful'){
                        rg++;
                        let obj = {}
                        obj.x1 = (a.x/105*100).toFixed(2);
                        obj.y1 = (a.y/68*100).toFixed(2);
                        unsuccessful.push(obj);
                    }
                }
            }
            /**for (let tag of a.tags){
                if (tag.id == 1801){
                    i++;
                }
                else {continue;}
            }
            if (i == 1){
                for (let tag of a.tags){
                    if (tag.id == 801){
                        let z = 0; let obj = {};
                        for (let position of a.positions){
                            z++;
                            if(z == 1){
                                obj.x1 = position.x;
                                obj.y1 = position.y;
                            }
                            else if (z == 2){
                                obj.x2 = position.x;
                                obj.y2 = position.y
                            }
                            else {continue}
                        }
                        high.push(obj); 
                    }
                    else if (tag.id == 802){
                        let z = 0; let obj = {};
                        for (let position of a.positions){
                            z++;
                            if(z == 1){
                                obj.x1 = position.x;
                                obj.y1 = position.y;
                            }
                            else if (z == 2){
                                obj.x2 = position.x;
                                obj.y2 = position.y
                            }
                            else {continue}
                        }
                        ground.push(obj); 
                    }
                    else {continue;}
                }
            }
            else{
                let z = 0; let obj = {};
                for (let position of a.positions){
                    z++;
                    if(z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y
                    }
                    else {continue}
                }
                unsuccessful.push(obj);
            }*/
        }
        let table = []; let left = {}; let right = {}; let total = {};
        let ret1 = {}
        /**for (let a of r){
            let obj = {}; let i = 0; let h = 0; let j = 0; let k = 0;
            for (let tag of a.tags){
                if (tag.id == 1801){
                    h = 1;
                }
                else if (tag.id == 802){
                    j = 1;
                }
                else if (tag.id == 301){
                    k = 1;
                }
                else {continue;}
            }
            if (h == 1){
                const re = await eventCtl.find({eventId: a.eventAfterId, eventSec: a.eventAfterTime, matchId: a.matchId, teamId: a.teamId});
                //console.log(re)
                for (let b of re){
                    let playerId = b.playerId;
                    if(!Object.hasOwnProperty.call(ret1, playerId)){//ret无playerId,tui
                        ret1[playerId] = { playerId, Crosses: 1, ground: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                    }else{//ret有playerId,tui 对应数值
                        ret1[playerId].Crosses = ret1[playerId].Crosses + 1; 
                        //ret[playerId].fxg = fg.fxg;
                        //ret[playerId].fyg = fg.fyg;
                    }
                    if (j == 1){
                        if(!Object.hasOwnProperty.call(ret1, playerId)){//ret无playerId,tui
                            ret1[playerId] = { playerId, Crosses: 1, ground: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                        }else{//ret有playerId,tui 对应数值
                            ret1[playerId].ground = ret1[playerId].ground + 1; 
                            //ret[playerId].fxg = fg.fxg;
                            //ret[playerId].fyg = fg.fyg;
                        }
                    }
                }
            }
            for (let position of a.positions){
                i++;
                if(i == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                }
                else if (i == 2){
                    obj.x2 = position.x;
                    obj.y2 = position.y
                }
                else {continue}
            }
            if (obj.y1 <= 50){
                lc++;
                if (h == 1){
                    lcs++;
                }
                if (j == 1){
                    lg++;
                }
                if (j == 1 && h == 0){
                    lgc++;
                }
                if (k == 1){
                    la++;
                }
                else {continue;}
            }
            else if (obj.y1 > 50){
                rc++;
                if (h == 1){
                    rcs++;
                }
                if (j == 1){
                    rg++;
                }
                if (j == 1 && h == 0){
                    rgc++;
                }
                if (k == 1){
                    ra++;
                }
                else {continue;}
            }
            else {continue;}
        }*/
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Crosses'] = parseFloat((a['Crosses All Match']/a.timePlayed*90).toFixed(1));
            obj['Accurate crosses'] = parseFloat((a['Crosses All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Crosses'] != 'none'){
                let Crosses = pf['Crosses'];
                if(!Object.hasOwnProperty.call(ret2, Crosses)){//ret无playerId,tui
                    ret2[Crosses] = { Crosses, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[Crosses].number = ret2[Crosses].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Accurate crosses'] != 'none'){
                let ac = pf['Accurate crosses'];
                if(!Object.hasOwnProperty.call(ret3, ac)){//ret无playerId,tui
                    ret3[ac] = { ac, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[ac].number = ret3[ac].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];let receiver = []; 
        var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[b]["Crosses"]-ret1[a]["Crosses"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            receiver.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["Crosses"]-ret2[b]["Crosses"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["ac"]-ret3[b]["ac"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Crosses'] = resultTwo;
        figure['Accurate crosses'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['crosses'] = parseFloat((a['Crosses All Match']/a.timePlayed*90).toFixed(1));
                figure['cccurate crosses'] = parseFloat((a['Crosses All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        left.name = 'Left'; left.Crosses = lc; left.successful = lcs; left.rate = ((lcs/lc || 0)*100).toFixed()+'%'; left.Unsuccessful = lg; left.keypass = lgc; left.xA = 0; left.Assists = la; table.push(left);
        right.name = 'Right'; right.Crosses = rc; right.successful = rcs; right.rate = ((rcs/rc || 0)*100).toFixed()+'%'; right.Unsuccessful = rg; right.keypass = rgc; right.xA = 0; right.Assists = ra; table.push(right); 
        total.name = 'Total'; total.Crosses = lc+rc; total.successful = lcs+rcs; total.rate = ((total.successful/total.Crosses || 0)*100).toFixed()+'%'; total.Unsuccessful = lg+rg; total.keypass = lgc+rgc; total.xA = 0; total.Assists = la+ra; table.push(total);
        //console.log(receiver)
        let Receiver = []
        for (let a of receiver){
            const player = await playerCtl.retrieve(a.playerId)
            //console.log(player)
            obj = {
                Receiver: player.shortName,
                Crosses: a.Crosses,
                ground: a.ground
            }
            Receiver.push(obj);
        }
        result.Unsuccessful = unsuccessful;
        result.Successful = successful;
        result['Key pass'] = Keypass;
        result.Table = table;
        result.Figure = figure;
        result.Receiver = Receiver; 
        ctx.body = result;
    })

    .get('/actions/crossupdate/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{type_id:5},{type_id:6},{type_id:7}],playerId:playerid});
        let result = {}; let unsuccessful = []; let successful = []; //let Keypass = [];
        let lc = 0, lcs = 0, lsa = 0, la = 0;
        let rc = 0, rcs = 0, rsa = 0, ra = 0;
        let ret1 = {}
        for (let a of r){
            let obj = {}
            obj.x1 = (a.x/105*100).toFixed(2);
            obj.y1 = (a.y/68*100).toFixed(2);
            obj.x2 = (a.end_x/105*100).toFixed(2);
            obj.y2 = (a.end_y/68*100).toFixed(2);
            let ptplayerId = a.passto_playerId
            if (a.y <= 34){
                lc++;
                if (a.result_name != 'Unsuccessful'){
                    lcs++;
                    successful.push(obj);
                    if(!Object.hasOwnProperty.call(ret1, ptplayerId)){//ret无playerId,tui
                        ret1[ptplayerId] = { playerId: parseInt(ptplayerId), Number: 1, xA: 0, 'Shot assist': 0, Assist: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                    }else{//ret有playerId,tui 对应数值
                        ret1[ptplayerId].Number = ret1[ptplayerId].Number + 1; 
                        //ret[playerId].fxg = fg.fxg;
                        //ret[playerId].fyg = fg.fyg;
                    }
                    if (a.result_name == 'Assist'){
                        la++;
                        ret1[ptplayerId].Assist = ret1[ptplayerId].Assist + 1; 
                    }
                    else {
                        if (a.eventafter_Id == 8 || a.eventafter_Id == 9 || a.eventafter_Id == 10){
                            lsa++;
                            ret1[ptplayerId]['Shot assist'] = ret1[ptplayerId]['Shot assist'] + 1;
                        }
                    }
                }
                else {
                    unsuccessful.push(obj);
                }
            }
            if (a.y > 34){
                rc++;
                if (a.result_name != 'Unsuccessful'){
                    rcs++;
                    successful.push(obj);
                    if(!Object.hasOwnProperty.call(ret1, ptplayerId)){//ret无playerId,tui
                        ret1[ptplayerId] = { playerId: parseInt(ptplayerId), Number: 1, xA: 0, 'Shot assist': 0, Assist: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                    }else{//ret有playerId,tui 对应数值
                        ret1[ptplayerId].Number = ret1[ptplayerId].Number + 1; 
                        //ret[playerId].fxg = fg.fxg;
                        //ret[playerId].fyg = fg.fyg;
                    }
                    if (a.result_name == 'Assist'){
                        ra++;
                        ret1[ptplayerId].Assist = ret1[ptplayerId].Assist + 1; 
                    }
                    else {
                        if (a.eventafter_Id == 8 || a.eventafter_Id == 9 || a.eventafter_Id == 10){
                        rsa++;
                            ret1[ptplayerId]['Shot assist'] = ret1[ptplayerId]['Shot assist'] + 1;
                        }
                    }
                }
                else {
                    unsuccessful.push(obj);
                }
            }
            /**for (let tag of a.tags){
                if (tag.id == 1801){
                    i++;
                }
                else {continue;}
            }
            if (i == 1){
                for (let tag of a.tags){
                    if (tag.id == 801){
                        let z = 0; let obj = {};
                        for (let position of a.positions){
                            z++;
                            if(z == 1){
                                obj.x1 = position.x;
                                obj.y1 = position.y;
                            }
                            else if (z == 2){
                                obj.x2 = position.x;
                                obj.y2 = position.y
                            }
                            else {continue}
                        }
                        high.push(obj); 
                    }
                    else if (tag.id == 802){
                        let z = 0; let obj = {};
                        for (let position of a.positions){
                            z++;
                            if(z == 1){
                                obj.x1 = position.x;
                                obj.y1 = position.y;
                            }
                            else if (z == 2){
                                obj.x2 = position.x;
                                obj.y2 = position.y
                            }
                            else {continue}
                        }
                        ground.push(obj); 
                    }
                    else {continue;}
                }
            }
            else{
                let z = 0; let obj = {};
                for (let position of a.positions){
                    z++;
                    if(z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y
                    }
                    else {continue}
                }
                unsuccessful.push(obj);
            }*/
        }
        //console.log(ret1)
        let table = []; let left = {}; let right = {}; let total = {};
        //let ret1 = {}
        /**for (let a of r){
            let obj = {}; let i = 0; let h = 0; let j = 0; let k = 0;
            for (let tag of a.tags){
                if (tag.id == 1801){
                    h = 1;
                }
                else if (tag.id == 802){
                    j = 1;
                }
                else if (tag.id == 301){
                    k = 1;
                }
                else {continue;}
            }
            if (h == 1){
                const re = await eventCtl.find({eventId: a.eventAfterId, eventSec: a.eventAfterTime, matchId: a.matchId, teamId: a.teamId});
                //console.log(re)
                for (let b of re){
                    let playerId = b.playerId;
                    if(!Object.hasOwnProperty.call(ret1, playerId)){//ret无playerId,tui
                        ret1[playerId] = { playerId, Crosses: 1, ground: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                    }else{//ret有playerId,tui 对应数值
                        ret1[playerId].Crosses = ret1[playerId].Crosses + 1; 
                        //ret[playerId].fxg = fg.fxg;
                        //ret[playerId].fyg = fg.fyg;
                    }
                    if (j == 1){
                        if(!Object.hasOwnProperty.call(ret1, playerId)){//ret无playerId,tui
                            ret1[playerId] = { playerId, Crosses: 1, ground: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                        }else{//ret有playerId,tui 对应数值
                            ret1[playerId].ground = ret1[playerId].ground + 1; 
                            //ret[playerId].fxg = fg.fxg;
                            //ret[playerId].fyg = fg.fyg;
                        }
                    }
                }
            }
            for (let position of a.positions){
                i++;
                if(i == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                }
                else if (i == 2){
                    obj.x2 = position.x;
                    obj.y2 = position.y
                }
                else {continue}
            }
            if (obj.y1 <= 50){
                lc++;
                if (h == 1){
                    lcs++;
                }
                if (j == 1){
                    lg++;
                }
                if (j == 1 && h == 0){
                    lgc++;
                }
                if (k == 1){
                    la++;a['through_ball_success']
                if (h == 1){
                    rcs++;
                }
                if (j == 1){
                    rg++;
                }
                if (j == 1 && h == 0){
                    rgc++;
                }
                if (k == 1){
                    ra++;
                }
                else {continue;}
            }
            else {continue;}
        }*/
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        let cross = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            //obj['Crosses'] = parseFloat(((a['cross_total']/a.time_played || 0)*90).toFixed(1));
            obj['Accurate crosses'] = parseFloat((((a['cross_success']/a['cross_total'] || 0)/a.minutes_played || 0)*90).toFixed(2));
            playerfeatures.push(obj)
            const player = await playerCtl.find({playerId: a.playerId})
            for (let b of player){
                let obj1 = {
                    playerId: a.playerId,
                    playerName: b.playerName,
                    crossTotal: parseInt(a.cross_total),
                    crossSuccess: parseFloat(parseFloat(a['cross_success']/a['cross_total'] || 0).toFixed(2))
                }
                cross.push(obj1);
            }
        }
        //console.log(playerfeatures)
        /*let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Crosses'] != 'none'){
                let Crosses = pf['Crosses'];
                if(!Object.hasOwnProperty.call(ret2, Crosses)){//ret无playerId,tui
                    ret2[Crosses] = { Crosses, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[Crosses].number = ret2[Crosses].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }*/
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Accurate crosses'] != 'none'){
                let ac = pf['Accurate crosses'];
                if(!Object.hasOwnProperty.call(ret3, ac)){//ret无playerId,tui
                    ret3[ac] = { ac, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[ac].number = ret3[ac].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];let receiver = []; 
        var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[b]["Number"]-ret1[a]["Number"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            receiver.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        /*var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["Crosses"]-ret2[b]["Crosses"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }*/
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["ac"]-ret3[b]["ac"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        //figure['Crosses'] = resultTwo;
        figure['Accurate_crosses'] = resultThree;
        const playerInfor = await playerCtl.find({playerId: playerid})
        const playerFeature = await plyfeaCtl.find({playerId: playerid})
        for (let a of playerInfor){
            for (let b of playerFeature){
                result['playerId'] = parseInt(playerid);
                result['playerName'] = a.playerName;
                result['crossTotal'] = parseInt(b.cross_total);
                result['crossSuccess'] = parseFloat(parseFloat(b['cross_success']/b['cross_total'] || 0).toFixed(2));
                result['crossSuccess/90'] = parseFloat((((b['cross_success']/b['cross_total'] || 0)/b.minutes_played || 0)*90).toFixed(2));
                //console.log(((b['through_ball_success']/b['through_ball_total'])/b.minutes_played)*5400)
            }
        }
        /*for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['crosses'] = parseFloat(((a['cross_total']/a.time_played || 0)*90).toFixed(1));
                figure['acurate_crosses'] = parseFloat((((a['cross_success']/a['cross_total'] || 0)/a.time_played || 0)*90).toFixed(1));
            }
            else {continue;}
        }*/
        left.name = '左路'; left.Crosses = lc; left.rate = parseInt(((lcs/lc || 0)*100).toFixed()); left.xA = 0.87; left['Shot_assist'] = lsa; left.Assists = la; table.push(left);
        right.name = '右路'; right.Crosses = rc; right.rate = parseInt(((rcs/rc || 0)*100).toFixed()); right.xA = 0.92; right['Shot_assist'] = rsa; right.Assists = ra; table.push(right); 
        //total.name = 'Total'; total.Crosses = lc+rc; total.rate = (((lcs+rcs)/(lc+rc) || 0)*100).toFixed()+'%'; total.xA = 1.79; total['Shot_assist'] = lsa+rsa; total.Assists = la+ra; table.push(total);
        //console.log(receiver)
        let Receiver = [];
        let i = 0;
        for (let a of receiver){
            if (i < 4){
                //console.log(a)
                const player = await playerCtl.retrieve(a.playerId)
                //console.log(player)
                obj = {
                    Receiver: player.playerName,
                    Crosses: a.Number,
                    xA: 0,
                    'Shot_assist': a['Shot assist'],
                    Assist: a.Assist
                }
                Receiver.push(obj);
                i++;
            }
            else{
                break;
            }
        }
        result.Unsuccessful = unsuccessful;
        result.Successful = successful;
        result.Cross = cross;
        //result['Key pass'] = Keypass;
        result.Table = table;
        result.Figure = figure;
        result.Receiver = Receiver; 
        ctx.body = result;
    })

    .get('/actions/dribblesthird/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({eventId: 27,playerId:playerid});
        let result = {}; let zuobiao = {}; let keptpossession = []; let followbyshot = []; let followbygoal = [];
        let fd = 0, fk = 0, fs = 0, fso = 0, fg = 0, fxg = 0;
        let md = 0, mk = 0, ms = 0, mso = 0, mg = 0, mxg = 0;
        let dd = 0, dk = 0, ds = 0, dso = 0, dg = 0, dxg = 0;
        let gd = 0, gk = 0, gs = 0, gso = 0, gg = 0, gxg = 0;
        for (let a of r){
            let obj = {}
            obj.x = a.x;
            obj.y = a.y;
            //let obj = {}; let z = 0; let i = 0; let h = 0; let j = 0; let k = 0; let l = 0;
            //obj.x = a.startX;
            //obj.y = a.startY;
            /**for(let position of a.positions){
                z++;
                if (z == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                }
                else if (z == 2){
                    obj.x2 = position.x;
                    obj.y2 = position.y;
                }
                else{continue;}
            }*/
            if (obj.x >= 70){
                let obj1 = {}
                obj1.x = (obj.x/105*100).toFixed(2);
                obj1.y = (obj.y/68*100).toFixed(2);
                keptpossession.push(obj1);
                /**const pp = await playerCtl.retrieve(a.duelAgainst)
                for (let key of Object.keys(pp.role)){
                    let roles = pp.role[key]
                    if (key == 'code2'){
                        role = roles;
                    }
                    else {continue;}
                } 
                for (let tag of a.tags){
                    if (tag.id == 501 || tag.id == 502 || tag.id == 503 || tag.id == 504){
                        i = 1;
                    }
                    else if (tag.id == 1801){
                        h = 1;
                    }
                    else {continue;}
                }
                if (i == 1){
                    if (role == 'FW'){
                        fd++;
                        fxg+=a.xG;
                    }
                    else if (role == 'MD'){
                        md++;
                        mxg+=a.xG;
                    }
                    else if (role == 'DF'){
                        dd++;
                        dxg+=a.xG;
                    }
                    else if (role == 'GK'){
                        gd++;
                        gxg+=a.xG;
                    }
                    else {continue;}
                }
                if (a.eventAfterId == 10 || a.eventAfterId == 3){
                    j = 1;
                    const r1 = await eventCtl.find({eventId: a.eventAfterId, eventSec: a.eventAfterTime, matchId: a.matchId});
                    for (let b of r1){
                        for (let tag1 of b.tags){
                            if (tag1.id == 101){
                                k = 1;
                            }
                            else if (tag1.id == 1801){
                                l = 1;
                            }
                            else {continue;}
                        }
                    }
                }
                if (i == 1 && h == 1 && j == 0 && k==0){
                    //keptpossession.push(obj);
                    if (role == 'FW'){
                        fk++;
                    }
                    else if (role == 'MD'){
                        mk++;
                    }
                    else if (role == 'DF'){
                        dk++;
                    }
                    else if (role == 'GK'){
                        gk++;
                    }
                    else {continue;}
                }
                else if (i == 1 && h == 1 && j == 1 && k==0){
                    followbyshot.push(obj);
                    if (role == 'FW'){
                        fs++;
                    }
                    else if (role == 'MD'){
                        ms++;
                    }
                    else if (role == 'DF'){
                        ds++;
                    }
                    else if (role == 'GK'){
                        gs++;
                    }
                    else {continue;}
                    if (l == 1){
                        if (role == 'FW'){
                            fso++;
                        }
                        else if (role == 'MD'){
                            mso++;
                        }
                        else if (role == 'DF'){
                            dso++;
                        }
                        else if (role == 'GK'){
                            gso++;
                        }
                        else {continue;}
                    }
                }
                else if (i == 1 && h == 1 && j == 1 && k==1){
                    followbygoal.push(obj);
                    if (role == 'FW'){
                        fg++;
                    }
                    else if (role == 'MD'){
                        mg++;
                    }
                    else if (role == 'DF'){
                        dg++;
                    }
                    else if (role == 'GK'){
                        gg++;
                    }
                    else {continue;}
                }
                else {continue;}*/
            }
            else {continue;}
        }
        let table = []; let forward = {}; let midfielder = {}; let defender = {}; let goalkeeper = {}; let total = {};
        forward['Opponent position'] = 'FW'; forward.Dribbles = fd; forward['kept possession'] = fk; forward.rate = ((fk/fd || 0)*100).toFixed()+'%'; forward['Shots_after'] = fs; forward['on target'] = fso; forward.xG = fxg; forward['Goals after'] = fg; table.push(forward);
        midfielder['Opponent position'] = 'MD'; midfielder.Dribbles = md; midfielder['kept possession'] = mk; midfielder.rate = ((mk/md || 0)*100).toFixed()+'%'; midfielder['Shots_after'] = ms; midfielder['on target'] = mso; midfielder.xG = mxg; midfielder['Goals after'] = mg; table.push(midfielder);
        defender['Opponent position'] = 'DF'; defender.Dribbles = dd; defender['kept possession'] = dk; defender.rate = ((dk/dd || 0)*100).toFixed()+'%'; defender['Shots_after'] = ds; defender['on target'] = dso; defender.xG = dxg; defender['Goals after'] = dg; table.push(defender);
        goalkeeper['Opponent position'] = 'GK'; goalkeeper.Dribbles = gd; goalkeeper['kept possession'] = gk; goalkeeper.rate = ((gk/gd || 0)*100).toFixed()+'%'; goalkeeper['Shots_after'] = gs; goalkeeper['on target'] = gso; goalkeeper.xG = gxg; goalkeeper['Goals after'] = gg; table.push(goalkeeper);
        total['Opponent position'] = 'Total'; total.Dribbles = fd+md+dd+gd; total['kept possession'] = fk+mk+dk+gk; total.rate = ((total['kept possession']/total.Dribbles || 0)*100).toFixed()+'%'; total['Shots_after'] = fs+ms+ds+gs; total['on target'] = fso+mso+dso+gso; total.xG = fxg+mxg+dxg+gxg; total['Goals after'] = fg+mg+dg+gg; table.push(total);
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Dribbles'] = parseFloat((a['Dribbles in final third All Match']/a.timePlayed*90).toFixed(1));
            obj['Successful dribbles'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Dribbles'] != 'none'){
                let Dribbles = pf['Dribbles'];
                if(!Object.hasOwnProperty.call(ret2, Dribbles)){//ret无playerId,tui
                    ret2[Dribbles] = { Dribbles, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[Dribbles].number = ret2[Dribbles].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Successful dribbles'] != 'none'){
                let sd = pf['Successful dribbles'];
                if(!Object.hasOwnProperty.call(ret3, sd)){//ret无playerId,tui
                    ret3[sd] = { sd, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[sd].number = ret3[sd].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["Dribbles"]-ret2[b]["Dribbles"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["sd"]-ret3[b]["sd"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Dribbles'] = resultTwo;
        figure['Successful dribbles'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['dribbles'] = parseFloat((a['Dribbles in final third All Match']/a.timePlayed*90).toFixed(1));
                figure['successful dribbles'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        zuobiao['Kept possession'] = keptpossession;
        zuobiao['Followed by a shot'] = followbyshot;
        zuobiao['Followed by a goal'] = followbygoal;
        result.zuobiao = zuobiao;
        result.Figure = figure;
        result.Table = table;
        ctx.body = result;
    })

    .get('/actions/recoveriesthird/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({eventId: 31, playerId: playerid});
        //console.log(r)
        let result = {}; let zuobiao = {}; let counterpressing = []; let followbyshot = []; let followbygoal = [];
        let zr = 0, zs = 0, zso = 0, zg = 0, zxg = 0;
        let rr = 0, rs = 0, rso = 0, rg = 0, rxg = 0;
        let pr = 0, ps = 0, pso = 0, pg = 0, pxg = 0;
        let lr = 0, ls = 0, lso = 0, lg = 0, lxg = 0;
        for (let a of r){
            let obj = {}; let z = 0; let i = 0; let k = 0; let l = 0; let h = 0;
            obj.x = a.x;
            obj.y = a.y;
            if (obj.x >= 70){
                let obj1 = {}
                obj1.x = (obj.x/105*100).toFixed(2);
                obj1.y = (obj.y/68*100).toFixed(2);
                counterpressing.push(obj1);
                if (obj.x < 89 && obj.y >= 14 && obj.y <= 54){
                    zr++;
                }
                else if (obj.y > 54 && obj.y <= 105){
                    rr++;
                }
                else if (obj.x >= 89 && obj.y <= 54 && obj.y >= 14){
                    pr++;
                }
                else if (obj.y < 14 && obj.y >= 0){
                    lr++;
                }
            }
            /**for(let position of a.positions){
                z++;
                if (z == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                }
                else{continue;}
            }
            for(let tag of a.tags){
                if (tag.id == 1401){
                    h == 1;
                }
            }
            if (obj.x1 >= 66 && (a.recovery != 'none' || h == 1)){
                const r1 = await eventCtl.find({eventId: a.eventAfterId, eventSec: a.eventAfterTime, matchId: a.matchId});
                for (let b of r1){
                    if (b.eventId == 10 || b.subEventId == 33 || b.subEventId == 35){
                        i = 1
                    }
                    for (let tag1 of b.tags){
                        if (tag1.id == 101 && (b.eventId == 10 || b.subEventId == 33 || b.subEventId == 35)){
                            k = 1;
                        }
                        else if (tag1.id == 1801){
                            l = 1;
                        }
                        else {continue;}
                    }
                }
                if (obj.x1 > 95 && obj.y1 > 36.5 && obj.y1 < 63.5){
                    zr++;
                    zxg+=a.xG;
                }
                else if ((obj.y1 >= 80 && obj.y1 <= 100) || (obj.x1 <= 85 && obj.y1 >= 66)){
                    rr++;
                    rxg+=a.xG;
                }
                else if (obj.x1 > 85 && obj.y1 < 80 && obj.y1 > 20){
                    pr++;
                    pxg+=a.xG;
                }
                else if ((obj.y1 <= 20 && obj.y1 >= 0) || (obj.x1 <= 85 && obj.y1 <= 33)){
                    lr++;
                    lxg+=a.xG;
                }
                if (i == 1){
                    if (obj.x1 > 95 && obj.y1 > 36.5 && obj.y1 < 63.5){
                        zs++;
                    }
                    else if ((obj.y1 >= 80 && obj.y1 <= 100) || (obj.x1 <= 85 && obj.y1 >= 66)){
                        rs++;
                    }
                    else if (obj.x1 > 85 && obj.y1 < 80 && obj.y1 > 20){
                        ps++;
                    }
                    else if ((obj.y1 <= 20 && obj.y1 >= 0) || (obj.x1 <= 85 && obj.y1 <= 33)){
                        ls++;
                    }
                    //else {continue;}
                }
                if (i == 0 && k == 0 && a.recovery == 'counterPressing'){
                    counterpressing.push(obj);
                }
                else if (i == 1 && k == 0){
                    followbyshot.push(obj);
                    if (l == 1){
                        if (obj.x1 > 95 && obj.y1 > 36.5 && obj.y1 < 63.5){
                            zso++;
                        }
                        else if ((obj.y1 >= 80 && obj.y1 <= 100) || (obj.x1 <= 85 && obj.y1 >= 66)){
                            rso++;
                        }
                        else if (obj.x1 > 85 && obj.y1 < 80 && obj.y1 > 20){
                            pso++;
                        }
                        else if ((obj.y1 <= 20 && obj.y1 >= 0) || (obj.x1 <= 85 && obj.y1 <= 33)){
                            lso++;
                        }
                        //else {continue;}
                    }
                }
                else if (k == 1){
                    followbygoal.push(obj)
                    if (obj.x1 > 95 && obj.y1 > 36.5 && obj.y1 < 63.5){
                        zg++;
                    }
                    else if ((obj.y1 >= 80 && obj.y1 <= 100) || (obj.x1 <= 85 && obj.y1 >= 66)){
                        rg++;
                    }
                    else if (obj.x1 > 85 && obj.y1 < 80 && obj.y1 > 20){
                        pg++;
                    }
                    else if ((obj.y1 <= 20 && obj.y1 >= 0) || (obj.x1 <= 85 && obj.y1 <= 33)){
                        lg++;
                    }
                    //else {continue;}
                }
            }*/
            else {continue;}
        }
        table = [
            {Zone: 'Zone 14', Recoveries: zr, 'Shots after': zs, 'on target': zso, rate: ((zso/zs || 0)*100).toFixed()+'%', xG: zxg.toFixed(2), 'Goals after': zg},
            {Zone: 'Right flank', Recoveries: rr, 'Shots after': rs, 'on target': rso, rate: ((rso/rs || 0)*100).toFixed()+'%', xG: rxg.toFixed(2), 'Goals after': rg},
            {Zone: 'Penalty area', Recoveries: pr, 'Shots after': ps, 'on target': pso, rate: ((pso/ps || 0)*100).toFixed()+'%', xG: pxg.toFixed(2), 'Goals after': pg},
            {Zone: 'Left flank', Recoveries: lr, 'Shots after': ls, 'on target': lso, rate: ((lso/ls || 0)*100).toFixed()+'%', xG: lxg.toFixed(2), 'Goals after': lg},
            {Zone: 'Total', Recoveries: zr+rr+pr+lr, 'Shots after': zs+rs+ps+ls, 'on target': zso+rso+pso+lso, rate: (((zso+rso+pso+lso)/(zs+rs+ps+ls) || 0)*100).toFixed()+'%', xG: (zxg+rxg+pxg+lxg).toFixed(2), 'Goals after': zg+rg+pg+lg}
        ];
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Recoveries in final third'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
            obj['Dangerous recoveries'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Recoveries in final third'] != 'none'){
                let rft = pf['Recoveries in final third'];
                if(!Object.hasOwnProperty.call(ret2, rft)){//ret无playerId,tui
                    ret2[rft] = { rft, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[rft].number = ret2[rft].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Dangerous recoveries'] != 'none'){
                let dr = pf['Dangerous recoveries'];
                if(!Object.hasOwnProperty.call(ret3, dr)){//ret无playerId,tui
                    ret3[dr] = { dr, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[dr].number = ret3[dr].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["rft"]-ret2[b]["rft"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["dr"]-ret3[b]["dr"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Recoveries in final third'] = resultTwo;
        figure['Dangerous recoveries'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['recoveries in final third'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
                figure['dangerous recoveries'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        zuobiao.Counterpressing = counterpressing;
        zuobiao['With shot'] = followbyshot;
        zuobiao['Goal'] = followbygoal;
        result.zuobiao = zuobiao;
        result.Figure = figure;
        result.Table = table;
        ctx.body = result;
    })

    .get('/actions/recoveries/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({playerId:playerid});
        //console.log(r)
        let result = {}; let zuobiao = {}; let counterpressing = []; let interception = [];
        let or = 0, oc = 0, oi = 0, os = 0;
        let cr = 0, cc = 0, ci = 0, cs = 0;
        let fr = 0, fc = 0, fi = 0, fs = 0;
        for (let a of r){
            /**for(let position of a.positions){
                z++;
                if (z == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                }
                else{continue;}
            }
            for (let tag of a.tags){
                if (tag.id == 1601){
                    i = 1;
                }
                else if (tag.id == 1401){
                    k = 1;
                }
                else {continue;}
            }*/
            if (a.type_name == 'Ball_recovery'){
                if (a.x >= 0 && a.x <= 35){
                    or++;
                }
                else if (a.x > 35 && a.x < 70){
                    cr++;
                }
                else if (a.x >= 70 && a.x <= 105){
                    fr++;
                }
            }
            if (a.type_name == 'Interception'){
                if (a.x >= 0 && a.x <= 35){
                    oi++;
                }
                else if (a.x > 35 && a.x < 70){
                    ci++;
                }
                else if (a.x >= 70 && a.x <= 105){
                    fi++;
                }
                let obj = {};
                obj.x = (a.x/105*100).toFixed(2);
                obj.y = (a.y/68*100).toFixed(2);
                interception.push(obj);
            }
            if (a.type_name == 'Defensive_foul' && a.result_name == 'Successful'){
                if (a.x >= 0 && a.x <= 35){
                    oc++;
                }
                else if (a.x > 35 && a.x < 70){
                    cc++;
                }
                else if (a.x >= 70 && a.x <= 105){
                    fc++;
                }
                let obj = {};
                obj.x = (a.x/105*100).toFixed(2);
                obj.y = (a.y/68*100).toFixed(2);
                counterpressing.push(obj);
            }
            if (a.type_name == 'Tackle' && a.result_name == 'Successful'){
                if (a.x >= 0 && a.x <= 35){
                    os++;
                }
                else if (a.x > 35 && a.x < 70){
                    cs++;
                }
                else if (a.x >= 70 && a.x <= 105){
                    fs++;
                }
            }
            /**if (a.recovery != 'none' || k == 1){
                if (obj.x1 >= 0 && obj.x1 <= 33){
                    or++;
                }
                else if (obj.x1 > 33 && obj.x1 < 66){
                    cr++;
                }
                else if (obj.x1 >= 66 && obj.x1 <= 100){
                    fr++;
                }
                if (i == 1){
                    if (obj.x1 >= 0 && obj.x1 <= 33){
                        os++;
                    }
                    else if (obj.x1 > 33 && obj.x1 < 66){
                        cs++;
                    }
                    else if (obj.x1 >= 66 && obj.x1 <= 100){
                        fs++;
                    }
                    //else {continue;}
                }
                if (a.recovery == 'counterPressing'){
                    counterpressing.push(obj);
                    if (obj.x1 >= 0 && obj.x1 <= 33){
                        oc++;
                    }
                    else if (obj.x1 > 33 && obj.x1 < 66){
                        cc++;
                    }
                    else if (obj.x1 >= 66 && obj.x1 <= 100){
                        fc++;
                    }
                    //else {continue;}
                }
                //else {continue;}
            }
            if (k == 1){
                interception.push(obj);
                if (obj.x1 >= 0 && obj.x1 <= 33){
                    oi++;
                }
                else if (obj.x1 > 33 && obj.x1 < 66){
                    ci++;
                }
                else if (obj.x1 >= 66 && obj.x1 <= 100){
                    fi++;
                }
                //else {continue;}
            }
            else {continue;}*/
        }
        table = [
            {Zone: 'Own third', Recoveries: or, Counterpressing: oc, Interceptions: oi, 'Sliding tackles': os},
            {Zone: 'Central third', Recoveries: cr, Counterpressing: cc, Interceptions: ci, 'Sliding tackles': cs},
            {Zone: 'Final third', Recoveries: fr, Counterpressing: fc, Interceptions: fi, 'Sliding tackles': fs},
            {Zone: 'Total', Recoveries: or+cr+fr, Counterpressing: oc+cc+fc, Interceptions: oi+ci+fi, 'Sliding tackles': os+cs+fs}
        ];
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Recoveries'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
            obj['Counterpressing recoveries'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Recoveries'] != 'none'){
                let r = pf['Recoveries'];
                if(!Object.hasOwnProperty.call(ret2, r)){//ret无playerId,tui
                    ret2[r] = { r, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[r].number = ret2[r].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Counterpressing recoveries'] != 'none'){
                let cr = pf['Counterpressing recoveries'];
                if(!Object.hasOwnProperty.call(ret3, cr)){//ret无playerId,tui
                    ret3[cr] = { cr, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[cr].number = ret3[cr].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["r"]-ret2[b]["r"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["cr"]-ret3[b]["cr"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Recoveries'] = resultTwo;
        figure['Counterpressing recoveries'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['recoveries'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
                figure['counterpressing recoveries'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        zuobiao.Counterpressing = counterpressing;
        zuobiao.Interception = interception;
        result.zuobiao = zuobiao;
        result.Figure = figure;
        result.Table = table;
        ctx.body = result;
    })

    .get('/actions/losses/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{eventId:0},{eventId:1},{eventId:2},{eventId:3},{eventId:4},{eventId:5},{eventId:6},{eventId:7},{eventId:17},{eventId:20},{eventId:25}], playerId: playerid});
        let result = {}; let zuobiao = {}; let inaccurate = []; let lostduel = [];
        let ol = 0, cl = 0, fl = 0;
        for (let a of r){
            let obj = {}; let z = 0; let i = 0; let k = 0; let l = 0; let obj1 = {}
            //obj.x = a.startX;
            //obj.y = a.startY;
            if ((a.eventId == 17 || a.eventId == 20 || a.eventId == 25) && a.result_name == 'Unsuccessful'){
                if (a.x >= 0 && a.x <= 35){
                    ol++;
                }
                else if (a.x > 35 && a.x < 70){
                    cl++;
                }
                else if (a.x >= 70 && a.x <= 105){
                    fl++;
                }
                let obj = {}
                obj.x = (a.x/105*100).toFixed(2);
                obj.y = (a.y/68*100).toFixed(2);
                lostduel.push(obj)
            }
            if ((a.eventId == 0 || a.eventId == 1 || a.eventId == 2 || a.eventId == 3 || a.eventId == 4 || a.eventId == 5 || a.eventId == 6 || a.eventId == 7) && a.result_name == 'Unsuccessful'){
                if (a.x >= 0 && a.x <= 35){
                    ol++;
                }
                else if (a.x > 35 && a.x < 70){
                    cl++;
                }
                else if (a.x >= 70 && a.x <= 105){
                    fl++;
                }
                let obj1 = {}
                obj1.x1 = (a.x/105*100).toFixed(2);
                obj1.y1 = (a.y/68*100).toFixed(2);
                obj1.x2 = (a.end_x/105*100).toFixed(2);
                obj1.y2 = (a.end_y/68*100).toFixed(2);
                inaccurate.push(obj1)
            }
            /**for(let position of a.positions){
                z++;
                if (z == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                    obj1.x = position.x;
                    obj1.y = position.y;
                }
                else if (z == 2){
                    obj.x2 = position.x;
                    obj.y2 = position.y;
                }
                else{continue;}
            }
            for (let tag of a.tags){
                if (tag.id == 1802){
                    i = 1;
                }
                else if (tag.id == 701){
                    k = 1;
                }
                else {continue;}
            }
            if ((a.eventId == 8 || a.subEventId == 30 || a.subEventId == 32 || a.subEventId == 31 || a.subEventId == 36 || a.subEventId == 34) && i == 1){
                inaccurate.push(obj);
                if (obj.x1 >= 0 && obj.x1 <= 33){
                    ol++;
                }
                else if (obj.x1 > 33 && obj.x1 < 66){
                    cl++;
                }
                else if (obj.x1 >= 66 && obj.x1 <= 100){
                    fl++;
                }
            }
            else if (a.eventId == 1 && k == 1){
                lostduel.push(obj1);
                if (obj.x1 >= 0 && obj.x1 <= 33){
                    ol++;
                }
                else if (obj.x1 > 33 && obj.x1 < 66){
                    cl++;
                }
                else if (obj.x1 >= 66 && obj.x1 <= 100){
                    fl++;
                }
                //else {continue;}
            }
            else {continue;}*/
        }
        table = [
            {Zone: 'Own third', losses: ol},
            {Zone: 'Central third', losses: cl},
            {Zone: 'Final third', losses: fl},
            {Zone: 'Total', losses: ol+cl+fl}
        ];
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Losses'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
            obj['Losses index'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Losses'] != 'none'){
                let Losses = pf['Losses'];
                if(!Object.hasOwnProperty.call(ret2, Losses)){//ret无playerId,tui
                    ret2[Losses] = { Losses, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[Losses].number = ret2[Losses].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Losses index'] != 'none'){
                let li = pf['Losses index'];
                if(!Object.hasOwnProperty.call(ret3, li)){//ret无playerId,tui
                    ret3[li] = { li, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[li].number = ret3[li].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["Losses"]-ret2[b]["Losses"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["li"]-ret3[b]["li"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Losses'] = resultTwo;
        figure['Losses index'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['losses'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
                figure['losses index'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        zuobiao['Inaccurate pass'] = inaccurate;
        zuobiao['Lost duel'] = lostduel;
        result.zuobiao = zuobiao;
        result.Figure = figure;
        result.Table = table;
        ctx.body = result;
    })

    .get('/actions/counterattacks/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{eventId:0},{eventId:1},{eventId:2},{eventId:3},{eventId:4},{eventId:5},{eventId:6},{eventId:7},{eventId:8},{eventId:9},{eventId:10},{eventId:26},{eventId:27}], playerId: playerid});
        let result = {}; let zuobiao = {}; let inaccurate = []; let accurate = []; let acceleration = []; let dribblewon = []; let dribblelost = [];
        let shot = [];
        //let ol = 0, cl = 0, fl = 0;
        for (let a of r){
            let obj = {}; let z = 0; let i = 0; let k = 0; let j = 0; let l = 0; let obj1 = {}
            obj.x1 = (a.x/105*100).toFixed(2);
            obj.y1 = (a.y/68*100).toFixed(2);
            obj.x2 = (a.end_x/105*100).toFixed(2);
            obj.y2 = (a.end_y/68*100).toFixed(2);
            if (a.eventId == 0 || a.eventId == 1 || a.eventId == 2 || a.eventId == 3 || a.eventId == 4 || a.eventId == 5 || a.eventId == 6 || a.eventId == 7){
                if (a.result_name == 'Successful'){
                    accurate.push(obj);
                }
                else if(a.result_name == 'Unsuccessful'){
                    inaccurate.push(obj);
                }
            }
            else if (a.eventId == 26){
                if (a.result_name == 'Successful'){
                    acceleration.push(obj);
                }
                else if(a.result_name == 'Unsuccessful'){
                    let obj1 = {}
                    obj1.x = obj.x2;
                    obj1.y = obj.y2;
                    dribblelost.push(obj1)
                }
            }
            else if (a.eventId == 27){
                let obj1 = {}
                obj1.x = obj.x1;
                obj1.y = obj.y1;
                dribblewon.push(obj1)
            }
            else if (a.eventId == 8 || a.eventId == 9 || a.eventId == 10){
                let obj1 = {}
                obj1.x = obj.x1;
                obj1.y = obj.y1;
                shot.push(obj1)
            }
            /**for(let position of a.positions){
                z++;
                if (z == 1){
                    obj.x1 = position.x;
                    obj.y1 = position.y;
                    obj1.x = position.x;
                    obj1.y = position.y;
                }
                else if (z == 2){
                    obj.x2 = position.x;
                    obj.y2 = position.y;
                }
                else{continue;}
            }
            for (let tag of a.tags){
                if (tag.id == 1802){
                    i = 1;
                }
                else if (tag.id == 1801){
                    h = 1;
                }
                else if (tag.id == 501 || tag.id == 502 || tag.id == 503 || tag.id == 504){
                    j = 1;
                }
                else if (tag.id == 703){
                    k = 1;
                }
                else if (tag.id == 701){
                    l = 1;
                }
                else {continue;}
            }
            if ((a.eventId == 8 || a.subEventId == 30 || a.subEventId == 32 || a.subEventId == 31 || a.subEventId == 36 || a.subEventId == 34) && i == 1){
                inaccurate.push(obj);
            }
            else if ((a.eventId == 8 || a.subEventId == 30 || a.subEventId == 32 || a.subEventId == 31 || a.subEventId == 36 || a.subEventId == 34) && h == 1){
                accurate.push(obj);
                //else {continue;}
            }
            else if (a.subEventId == 70){
                acceleration.push(obj);
            }
            else if (j == 1 && k == 1){
                dribblewon.push(obj1);
            }
            else if (j == 1 && l == 1){
                dribblelost.push(obj1);
            }
            else if (a.eventId == 10 || a.subEventId == 33 || a.subEventId == 35){
                shot.push(obj1);
            }
            else {continue;}*/
        }
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['xGChain in counterattacks'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
            obj['% of xGChain in counterattacks'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['xGChain in counterattacks'] != 'none'){
                let num = pf['xGChain in counterattacks'];
                if(!Object.hasOwnProperty.call(ret2, num)){//ret无playerId,tui
                    ret2[num] = { num, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[num].number = ret2[num].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['% of xGChain in counterattacks'] != 'none'){
                let rate = pf['% of xGChain in counterattacks'];
                if(!Object.hasOwnProperty.call(ret3, rate)){//ret无playerId,tui
                    ret3[rate] = { rate, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[rate].number = ret3[rate].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["num"]-ret2[b]["num"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["rate"]-ret3[b]["rate"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['xGChain in counterattacks'] = resultTwo;
        figure['% of xGChain in counterattacks'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['xgChain in counterattacks'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
                figure['rate of xGChain in counterattacks'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        zuobiao['Inaccurate pass'] = inaccurate;
        zuobiao['Accurate pass'] = accurate;
        zuobiao.Acceleration = acceleration;
        zuobiao['Won dribble'] = dribblewon;
        zuobiao['Lost dribble'] = dribblelost;
        zuobiao.Shot = shot;
        result.zuobiao = zuobiao;
        result.Figure = figure;
        ctx.body = result;
    })

    .get('/actions/pass/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{type_id:0},{type_id:1},{type_id:2},{type_id:3},{type_id:4}], playerId: playerid});
        let result = {}; //let zuobiao = {}; let inaccurate = []; let accurate = []; let acceleration = []; let dribblewon = []; let dribblelost = [];
        let bp = 0; let bpa = 0; let bk = 0; let bt = 0; let bl = 0;// let plfa= 0; let prf = 0; let prfd = 0; let prfa = 0; let pll = 0; let plld = 0; let plla = 0; let prl = 0; let prld = 0; let prla = 0; let plb = 0; let plbd = 0; let plba = 0; let prb = 0; let prbd = 0; let prba = 0; let pb = 0; let pbd = 0; let pba = 0;
        let cp = 0; let cpa = 0; let ck = 0; let ct = 0; let cl = 0;// let llfa= 0; let lrf = 0; let lrfd = 0; let lrfa = 0; let lll = 0; let llld = 0; let llla = 0; let lrl = 0; let lrld = 0; let lrla = 0; let llb = 0; let llbd = 0; let llba = 0; let lrb = 0; let lrbd = 0; let lrba = 0; let lb = 0; let lbd = 0; let lba = 0;
        let fp = 0; let fpa = 0; let fk = 0; let ft = 0; let fl = 0;// let rlfa= 0; let rrf = 0; let rrfd = 0; let rrfa = 0; let rll = 0; let rlld = 0; let rlla = 0; let rrl = 0; let rrld = 0; let rrla = 0; let rlb = 0; let rlbd = 0; let rlba = 0; let rrb = 0; let rrbd = 0; let rrba = 0; let rb = 0; let rbd = 0; let rba = 0;
        //pass_successful = []; pass_unsuccessful = []
        for (let a of r){
            let obj = {}
            obj.x1 = (a.x/105*100).toFixed(2);
            obj.y1 = (a.y/68*100).toFixed(2);
            obj.x2 = (a.end_x/105*100).toFixed(2);
            obj.y2 = (a.end_y/68*100).toFixed(2);
            if (a.x >= 0 && a.x <= 35){
                bp++;
                if (a.result_name != 'Unsuccessful'){
                    //pass_successful.push(obj)
                    bpa++
                    if (a.result_name == 'Key_pass'){
                        bk++
                    }
                }
                else {
                    //pass_unsuccessful.push(obj)
                }
                if (a.eventId == 1){
                    bl++
                }
                if (a.attribute_name == 'Through_ball'){
                    bt++
                }
            }
            else if (a.x > 35 && a.x < 70){
                cp++;
                if (a.result_name != 'Unsuccessful'){
                    //pass_successful.push(obj)
                    cpa++
                    if (a.result_name == 'Key_pass'){
                        ck++
                    }
                }
                else {
                    //pass_unsuccessful.push(obj)
                }
                if (a.eventId == 1){
                    cl++
                }
                if (a.attribute_name == 'Through_ball'){
                    ct++
                }
            }
            else if (a.x >= 70 && a.x <= 105){
                fp++;
                if (a.result_name != 'Unsuccessful'){
                    //pass_successful.push(obj)
                    fpa++
                    if (a.result_name == 'Key_pass'){
                        fk++
                    }
                }
                else {
                    //pass_unsuccessful.push(obj)
                }
                if (a.eventId == 1){
                    fl++
                }
                if (a.attribute_name == 'Through_ball'){
                    ft++
                }
            } 
        }
        let table = [
            {zone: '进攻三区', pass: fp, 'passAccuracy': fpa, rate: parseFloat((fpa/fp || 0).toFixed(2)), 'keyPass': fk, 'throughPass': ft, 'longPass': fl},
            {zone: '中场三区', pass: cp, 'passAccuracy': cpa, rate: parseFloat((cpa/cp || 0).toFixed(2)), 'keyPass': ck, 'throughPass': ct, 'longPass': cl},
            {zone: '防守三区', pass: bp, 'passAccuracy': bpa, rate: parseFloat((bpa/bp || 0).toFixed(2)), 'keyPass': bk, 'throughPass': bt, 'longPass': bl},
            //{Zone: 'Total', pass: bp+cp+fp, 'passAccuracy': bpa+cpa+fpa, rate: (((bpa+cpa+fpa)/(bp+cp+fp) || 0)*100).toFixed(1)+'%', 'keyPass': bk+ck+fk, 'throughPass': bt+ct+ft, 'longPass': bl+cl+fl},
        ];
        const feaPlayer = await plyfeaCtl.find({playerId: playerid})
        //console.log(feaPlayer)
        let passZone = []
        for (let a of feaPlayer){
            passZone = [
                {
                    zone: 1,
                    x: "0",
                    y: "0",
                    passTotal: parseInt(a['zone1_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio1']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone1_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone1_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone1_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone1_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone1_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone1_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone1_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone1_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone1_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone1_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone1_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone1_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone1_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone1_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone1_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone1_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone1_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone1_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone1_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone1_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone1_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone1_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone1_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone1_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 2,
                    x: "33.5%",
                    y: "0",
                    passTotal: parseInt(a['zone2_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio2']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone2_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone2_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone2_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone2_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone2_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone2_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone2_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone2_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone2_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone2_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone2_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone2_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone2_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone2_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone2_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone2_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone2_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone2_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone2_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone2_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone2_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone2_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone2_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone2_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 3,
                    x: "67%",
                    y: "0",
                    passTotal: parseInt(a['zone3_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio3']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone3_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone3_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone3_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone3_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone3_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone3_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone3_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone3_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone3_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone3_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone3_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone3_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone3_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone3_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone3_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone3_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone3_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone3_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone3_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone3_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone3_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone3_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone3_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone3_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 4,
                    x: "0",
                    y: "33.5%",
                    passTotal: parseInt(a['zone4_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio4']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone4_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone4_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone4_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone4_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone4_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone4_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone4_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone4_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone4_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone4_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone4_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone4_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone4_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone4_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone4_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone4_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone4_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone4_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone4_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone4_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone4_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone4_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone4_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone4_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 5,
                    x: "33.5%",
                    y: "33.5%",
                    passTotal: parseInt(a['zone5_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio5']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone5_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone5_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone5_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone5_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone5_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone5_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone5_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone5_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone5_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone5_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone5_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone5_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone5_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone5_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone5_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone5_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone5_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone5_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone5_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone5_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone5_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone5_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone5_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone5_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 6,
                    x: "67%",
                    y: "33.5%",
                    passTotal: parseInt(a['zone6_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio6']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone6_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone6_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone6_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone6_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone6_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone6_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone6_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone6_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone6_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone6_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone6_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone6_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone6_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone6_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone6_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone6_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone6_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone6_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone6_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone6_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone6_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone6_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone6_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone6_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 7,
                    x: "0",
                    y: "67%",
                    passTotal: parseInt(a['zone7_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio7']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone7_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone7_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone7_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone7_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone7_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone7_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone7_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone7_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone7_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone7_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone7_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone7_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone7_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone7_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone7_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone7_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone7_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone7_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone7_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone7_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone7_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone7_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone7_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone7_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 8,
                    x: "33.5%",
                    y: "67%",
                    passTotal: parseInt(a['zone8_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio8']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone8_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone8_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone8_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone8_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone8_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone8_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone8_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone8_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone8_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone8_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone8_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone8_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone8_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone8_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone8_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone8_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone8_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone8_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone8_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone8_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone8_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone8_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone8_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone8_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                },
                {
                    zone: 9,
                    x: "67%",
                    y: "67%",
                    passTotal: parseInt(a['zone9_pass']),
                    passRatio: parseFloat(parseFloat(a['pass_ratio9']).toFixed(2)),
                    roseData: [
                        {
                            angle: '0-30',
                            value: parseInt(a['zone9_30_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone9_60_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone9_90_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone9_120_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone9_150_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone9_180_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone9_210_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone9_240_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone9_270_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone9_300_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone9_330_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone9_360_succ']),
                            type: '成功传球'
                        },
                        {
                            angle: '0-30',
                            value: parseInt(a['zone9_30_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '31-60',
                            value: parseInt(a['zone9_60_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '61-90',
                            value: parseInt(a['zone9_90_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '91-120',
                            value: parseInt(a['zone9_120_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '121-150',
                            value: parseInt(a['zone9_150_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '151-180',
                            value: parseInt(a['zone9_180_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-180--151',
                            value: parseInt(a['zone9_210_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-150--121',
                            value: parseInt(a['zone9_240_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-120--91',
                            value: parseInt(a['zone9_270_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-90--61',
                            value: parseInt(a['zone9_300_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-60--31',
                            value: parseInt(a['zone9_330_unsucc']),
                            type: '失败传球'
                        },
                        {
                            angle: '-30-0',
                            value: parseInt(a['zone9_360_unsucc']),
                            type: '失败传球'
                        }
                    ]
                }
            ]
            rosetotal = [
                {
                    angle: '0-30',
                    value: parseInt(a['success_30']),
                    type: '成功传球'
                },
                {
                    angle: '31-60',
                    value: parseInt(a['success_60']),
                    type: '成功传球'
                },
                {
                    angle: '61-90',
                    value: parseInt(a['success_90']),
                    type: '成功传球'
                },
                {
                    angle: '91-120',
                    value: parseInt(a['success_120']),
                    type: '成功传球'
                },
                {
                    angle: '121-150',
                    value: parseInt(a['success_150']),
                    type: '成功传球'
                },
                {
                    angle: '151-180',
                    value: parseInt(a['success_180']),
                    type: '成功传球'
                },
                {
                    angle: '-180--151',
                    value: parseInt(a['success_210']),
                    type: '成功传球'
                },
                {
                    angle: '-150--121',
                    value: parseInt(a['success_240']),
                    type: '成功传球'
                },
                {
                    angle: '-120--91',
                    value: parseInt(a['success_270']),
                    type: '成功传球'
                },
                {
                    angle: '-90--61',
                    value: parseInt(a['success_300']),
                    type: '成功传球'
                },
                {
                    angle: '-60--31',
                    value: parseInt(a['success_330']),
                    type: '成功传球'
                },
                {
                    angle: '-30-0',
                    value: parseInt(a['success_360']),
                    type: '成功传球'
                },
                {
                    angle: '0-30',
                    value: parseInt(a['unsuccess_30']),
                    type: '失败传球'
                },
                {
                    angle: '31-60',
                    value: parseInt(a['unsuccess_60']),
                    type: '失败传球'
                },
                {
                    angle: '61-90',
                    value: parseInt(a['unsuccess_90']),
                    type: '失败传球'
                },
                {
                    angle: '91-120',
                    value: parseInt(a['unsuccess_120']),
                    type: '失败传球'
                },
                {
                    angle: '121-150',
                    value: parseInt(a['unsuccess_150']),
                    type: '失败传球'
                },
                {
                    angle: '151-180',
                    value: parseInt(a['unsuccess_180']),
                    type: '失败传球'
                },
                {
                    angle: '-180--151',
                    value: parseInt(a['unsuccess_210']),
                    type: '失败传球'
                },
                {
                    angle: '-150--121',
                    value: parseInt(a['unsuccess_240']),
                    type: '失败传球'
                },
                {
                    angle: '-120--91',
                    value: parseInt(a['unsuccess_270']),
                    type: '失败传球'
                },
                {
                    angle: '-90--61',
                    value: parseInt(a['unsuccess_300']),
                    type: '失败传球'
                },
                {
                    angle: '-60--31',
                    value: parseInt(a['unsuccess_330']),
                    type: '失败传球'
                },
                {
                    angle: '-30-0',
                    value: parseInt(a['unsuccess_360']),
                    type: '失败传球'
                }
            ]
        }
        const fea = await plyfeaCtl.list();
        let playerfeatures = [];
        let playerpass = []
        for (let a of fea){
            /*let obj = {}
            obj.playerId = a.playerId;
            //obj.teamId = a.teamId;
            //obj.competitionId = a.competitionId;
            obj.pass_total = parseFloat(((a['pass_total']/a.time_played || 0)*90).toFixed());
            obj.pass_success = parseFloat(((a['pass_success']/a.time_played || 0)*90).toFixed());
            playerfeatures.push(obj);*/
            const player = await playerCtl.find({playerId: a.playerId})
            for (let b of player){
                let obj1 = {
                    playerId: a.playerId,
                    playerName: b.playerName,
                    passTotal: parseInt(a.pass_total),
                    passAccuracy: parseFloat(parseFloat(a.pass_success/100).toFixed(2))
                }
                playerpass.push(obj1);
            }
        }
        //console.log(playerfeatures)
        //console.log(playerfeatures)
        /*let ret1 = {};
        for( let pf of playerfeatures){
            if (pf.pass_total != 'none'){
                let pass_total = pf.pass_total;
                if(!Object.hasOwnProperty.call(ret1, pass_total)){//ret无playerId,tui
                    ret1[pass_total] = { pass_total, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret1[pass_total].number = ret1[pass_total].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf.pass_success != 'none'){
                let pa = pf.pass_success;
                if(!Object.hasOwnProperty.call(ret2, pa)){//ret无playerId,tui
                    ret2[pa] = { pa, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[pa].number = ret2[pa].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultOne = []; let resultTwo = [];// let resultThree = [];
        var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[a]["pass_total"]-ret1[b]["pass_total"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultOne.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["pa"]-ret2[b]["pa"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['pass_total/90'] = resultOne;
        figure['pass_accuracy/90'] = resultTwo;*/
        //result['Through passes'] = resultThree;
        const playerInfor = await playerCtl.find({playerId: playerid})
        const playerFeature = await plyfeaCtl.find({playerId: playerid})
        for (let a of playerInfor){
            for (let b of playerFeature){
                result['playerId'] = parseInt(playerid);
                result['playerName'] = a.playerName;
                result['passTotal'] = parseInt(b.pass_total);
                result['passAccuracy'] = parseFloat(parseFloat(b.pass_success/100).toFixed(2));
            }
        }
        /*for (let a of fea){
            if (a.playerId == playerid){
                result['playerId'] = a.playerId;
                result['playerName'] = 
                result['pass total'] = parseFloat(((a['pass_total']/a.time_played || 0)*90).toFixed());
                result['pass accuracy'] = parseFloat(((a['pass_success']/a.time_played || 0)*90).toFixed());
                //result['through passes'] = parseFloat((a['Through passes All Match']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }*/
        //result['accurate pass'] = pass_successful;
        //result['inaccurate pass'] = pass_unsuccessful;
        result['PassZone'] = passZone;
        result['RoseTotal'] = rosetotal
        result['playerPass'] = playerpass;
        //result['Figure'] = figure;
        result['Table'] = table;
        ctx.body = result;
    })

    .get('/actions/throughpass/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{type_id:0},{type_id:1},{type_id:4}], playerId: playerid});
        let result = {}; //let zuobiao = {}; let inaccurate = []; let accurate = []; let acceleration = []; let dribblewon = []; let dribblelost = [];
        let btp = 0; let btpa = 0; let btk = 0; //let bt = 0; let bl = 0;// let plfa= 0; let prf = 0; let prfd = 0; let prfa = 0; let pll = 0; let plld = 0; let plla = 0; let prl = 0; let prld = 0; let prla = 0; let plb = 0; let plbd = 0; let plba = 0; let prb = 0; let prbd = 0; let prba = 0; let pb = 0; let pbd = 0; let pba = 0;
        let ctp = 0; let ctpa = 0; let ctk = 0; //let ct = 0; let cl = 0;// let llfa= 0; let lrf = 0; let lrfd = 0; let lrfa = 0; let lll = 0; let llld = 0; let llla = 0; let lrl = 0; let lrld = 0; let lrla = 0; let llb = 0; let llbd = 0; let llba = 0; let lrb = 0; let lrbd = 0; let lrba = 0; let lb = 0; let lbd = 0; let lba = 0;
        let ftp = 0; let ftpa = 0; let ftk = 0; //let ft = 0; let fl = 0;// let rlfa= 0; let rrf = 0; let rrfd = 0; let rrfa = 0; let rll = 0; let rlld = 0; let rlla = 0; let rrl = 0; let rrld = 0; let rrla = 0; let rlb = 0; let rlbd = 0; let rlba = 0; let rrb = 0; let rrbd = 0; let rrba = 0; let rb = 0; let rbd = 0; let rba = 0;
        let throughpass_successful = []; let throughpass_unsuccessful = []
        for (let a of r){
            let obj = {}
            obj.x1 = (a.x/105*100).toFixed(2);
            obj.y1 = (a.y/68*100).toFixed(2);
            obj.x2 = (a.end_x/105*100).toFixed(2);
            obj.y2 = (a.end_y/68*100).toFixed(2);
            if (a.attribute_id == 0 && a.x >= 0 && a.x <= 35){
                btp++;
                if (a.result_name != 'Unsuccessful'){
                    throughpass_successful.push(obj)
                    btpa++
                    if (a.result_name == 'Key_pass'){
                        btk++
                    }
                }
                else {
                    throughpass_unsuccessful.push(obj)
                }
            }
            else if (a.attribute_id == 0 && a.x > 35 && a.x < 70){
                ctp++;
                if (a.result_name != 'Unsuccessful'){
                    throughpass_successful.push(obj)
                    ctpa++
                    if (a.result_name == 'Key_pass'){
                        ctk++
                    }
                }
                else {
                    throughpass_unsuccessful.push(obj)
                }
            }
            else if (a.attribute_id == 0 && a.x >= 70 && a.x <= 105){
                ftp++;
                if (a.result_name != 'Unsuccessful'){
                    throughpass_successful.push(obj)
                    ftpa++
                    if (a.result_name == 'Key_pass'){
                        ftk++
                    }
                }
                else {
                    throughpass_unsuccessful.push(obj)
                }
            } 
        }
        let table = [
            {zone: '进攻三区', through_pass: ftp, 'passAccuracy': ftpa, rate: parseFloat((ftpa/ftp || 0).toFixed(2)), 'keyPass': ftk},
            {zone: '中场三区', through_pass: ctp, 'passAccuracy': ctpa, rate: parseFloat((ctpa/ctp || 0).toFixed(2)), 'keyPass': ctk},
            {zone: '防守三区', through_pass: btp, 'passAccuracy': btpa, rate: parseFloat((btpa/btp || 0).toFixed(2)), 'keyPass': btk},
            //{Zone: 'Total', through_pass: btp+ctp+ftp, 'pass_accuracy': btpa+ctpa+ftpa, rate: (((btpa+ctpa+ftpa)/(btp+ctp+ftp) || 0)*100).toFixed(1)+'%', 'key_pass': btk+ctk+ftk},
        ];
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        let throughpass = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            //obj.teamId = a.teamId;
            //obj.competitionId = a.competitionId;
            //obj.pass_total = parseFloat(((a['through_ball_total']/a.time_played || 0)*90).toFixed(1));
            obj.pass_success = parseFloat((((a['through_ball_success']/a['through_ball_total'] || 0)/a.minutes_played || 0)*90).toFixed(2));
            playerfeatures.push(obj)
            const player = await playerCtl.find({playerId: a.playerId})
            for (let b of player){
                let obj1 = {
                    playerId: a.playerId,
                    playerName: b.playerName,
                    throughPassTotal: parseInt(a.through_ball_total),
                    throughPassAccuracy: parseFloat(parseFloat(a.through_ball_success_rate).toFixed(2))
                }
                throughpass.push(obj1);
            }
        }
        /*i = 0
        for (let a of throughpass){
            i++
        }
        console.log(i)*/
        //console.log(playerfeatures)
        /*let ret1 = {};
        for( let pf of playerfeatures){
            if (pf.pass_total != 'none'){
                let pass_total = pf.pass_total;
                if(!Object.hasOwnProperty.call(ret1, pass_total)){//ret无playerId,tui
                    ret1[pass_total] = { through_ball: pass_total, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret1[pass_total].number = ret1[pass_total].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }*/
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf.pass_success != 'none'){
                let pa = pf.pass_success;
                if(!Object.hasOwnProperty.call(ret2, pa)){//ret无playerId,tui
                    ret2[pa] = { tpa: pa, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[pa].number = ret2[pa].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultOne = []; let resultTwo = [];// let resultThree = [];
        /*var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[a]["through_ball"]-ret1[b]["through_ball"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultOne.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }*/
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["tpa"]-ret2[b]["tpa"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        //figure['through_ball_total/90'] = resultOne;
        figure['throughPassAccuracy/90'] = resultTwo;
        //result['Through passes'] = resultThree;
        const playerInfor = await playerCtl.find({playerId: playerid})
        const playerFeature = await plyfeaCtl.find({playerId: playerid})
        for (let a of playerInfor){
            for (let b of playerFeature){
                result['playerId'] = parseInt(playerid);
                result['playerName'] = a.playerName;
                result['throughPassTotal'] = parseInt(b.through_ball_total);
                result['throughPassAccuracy'] = parseFloat(parseFloat(b.through_ball_success_rate).toFixed(2));
                result['throughPassAccuracy/90'] = parseFloat((((b['through_ball_success']/b['through_ball_total'] || 0)/b.minutes_played || 0)*90).toFixed(2));
                //console.log(((b['through_ball_success']/b['through_ball_total'])/b.minutes_played)*5400)
            }
        }
        /*for (let a of fea){
            if (a.playerId == playerid){
                result['playerId'] = a.playerId;
                result['through_ball_total'] = parseFloat(((a['through_ball_total']/a.time_played || 0)*90).toFixed(1));
                result['through_ball_accuracy'] = parseFloat((((a['through_ball_success']/a['through_ball_total'] || 0)/a.time_played || 0)*90).toFixed(2));
                //result['through passes'] = parseFloat((a['Through passes All Match']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }*/
        result['accurate_through_ball'] = throughpass_successful;
        result['inaccurate_through_ball'] = throughpass_unsuccessful;
        result['throughPass'] = throughpass;
        result['Figure'] = figure;
        result['Table'] = table;
        ctx.body = result;
    })

    .get('/actions/longpass/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({type_id:1, playerId: playerid});
        let result = {}; //let zuobiao = {}; let inaccurate = []; let accurate = []; let acceleration = []; let dribblewon = []; let dribblelost = [];
        let blp = 0; let blpa = 0; let blk = 0; //let bt = 0; let bl = 0;// let plfa= 0; let prf = 0; let prfd = 0; let prfa = 0; let pll = 0; let plld = 0; let plla = 0; let prl = 0; let prld = 0; let prla = 0; let plb = 0; let plbd = 0; let plba = 0; let prb = 0; let prbd = 0; let prba = 0; let pb = 0; let pbd = 0; let pba = 0;
        let clp = 0; let clpa = 0; let clk = 0; //let ct = 0; let cl = 0;// let llfa= 0; let lrf = 0; let lrfd = 0; let lrfa = 0; let lll = 0; let llld = 0; let llla = 0; let lrl = 0; let lrld = 0; let lrla = 0; let llb = 0; let llbd = 0; let llba = 0; let lrb = 0; let lrbd = 0; let lrba = 0; let lb = 0; let lbd = 0; let lba = 0;
        let flp = 0; let flpa = 0; let flk = 0; //let ft = 0; let fl = 0;// let rlfa= 0; let rrf = 0; let rrfd = 0; let rrfa = 0; let rll = 0; let rlld = 0; let rlla = 0; let rrl = 0; let rrld = 0; let rrla = 0; let rlb = 0; let rlbd = 0; let rlba = 0; let rrb = 0; let rrbd = 0; let rrba = 0; let rb = 0; let rbd = 0; let rba = 0;
        let longpass_successful = []; let longpass_unsuccessful = []
        for (let a of r){
            let obj = {}
            obj.x1 = (a.x/105*100).toFixed(2);
            obj.y1 = (a.y/68*100).toFixed(2);
            obj.x2 = (a.end_x/105*100).toFixed(2);
            obj.y2 = (a.end_y/68*100).toFixed(2);
            if (a.x >= 0 && a.x <= 35){
                blp++;
                if (a.result_name != 'Unsuccessful'){
                    longpass_successful.push(obj)
                    blpa++
                    if (a.result_name == 'Key_pass'){
                        blk++
                    }
                }
                else {
                    longpass_unsuccessful.push(obj)
                }
            }
            else if (a.x > 35 && a.x < 70){
                clp++;
                if (a.result_name != 'Unsuccessful'){
                    longpass_successful.push(obj)
                    clpa++
                    if (a.result_name == 'Key_pass'){
                        clk++
                    }
                }
                else {
                    longpass_unsuccessful.push(obj)
                }
            }
            else if (a.x >= 70 && a.x <= 105){
                flp++;
                if (a.result_name != 'Unsuccessful'){
                    longpass_successful.push(obj)
                    flpa++
                    if (a.result_name == 'Key_pass'){
                        flk++
                    }
                }
                else {
                    longpass_unsuccessful.push(obj)
                }
            } 
        }
        let table = [
            {zone: '进攻三区', longPass: flp, 'passAccuracy': flpa, rate: parseFloat((flpa/flp || 0).toFixed(1)), 'keyPass': flk},
            {zone: '中场三区', longPass: clp, 'passAccuracy': clpa, rate: parseFloat((clpa/clp || 0).toFixed(1)), 'keyPass': clk},
            {zone: '防守三区', longPass: blp, 'passAccuracy': blpa, rate: parseFloat((blpa/blp || 0).toFixed(1)), 'keyPass': blk},
            //{Zone: 'Total', long_pass: blp+clp+flp, 'pass_accuracy': blpa+clpa+flpa, rate: (((blpa+clpa+flpa)/(blp+clp+flp) || 0)*100).toFixed(1)+'%', 'key_pass': blk+clk+flk},
        ];
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        let longpass = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            //obj.teamId = a.teamId;
            //obj.competitionId = a.competitionId;
            //obj.pass_total = parseFloat(((a['long_pass_total']/a.time_played || 0)*90).toFixed());
            obj.pass_success = parseFloat((((a['long_pass_success']/a['long_pass_total'] || 0)/a.minutes_played || 0)*90).toFixed(2));
            playerfeatures.push(obj)
            const player = await playerCtl.find({playerId: a.playerId})
            for (let b of player){
                let obj1 = {
                    playerId: a.playerId,
                    playerName: b.playerName,
                    longPassTotal: parseInt(a.long_pass_total),
                    longPassAccuracy: parseFloat(parseFloat(a.long_pass_success_rate).toFixed(2))
                }
                longpass.push(obj1);
            }
        }
        //console.log(playerfeatures)
        //console.log(playerfeatures)
        /*let ret1 = {};
        for( let pf of playerfeatures){
            if (pf.pass_total != 'none'){
                let pass_total = pf.pass_total;
                if(!Object.hasOwnProperty.call(ret1, pass_total)){//ret无playerId,tui
                    ret1[pass_total] = { long_ball: pass_total, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret1[pass_total].number = ret1[pass_total].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }*/
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf.pass_success != 'none'){
                let pa = pf.pass_success;
                if(!Object.hasOwnProperty.call(ret2, pa)){//ret无playerId,tui
                    ret2[pa] = { lpa: pa, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[pa].number = ret2[pa].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultOne = []; let resultTwo = [];// let resultThree = [];
        /*var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[a]["long_ball"]-ret1[b]["long_ball"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultOne.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }*/
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["lpa"]-ret2[b]["lpa"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        //figure['long_ball_total/90'] = resultOne;
        figure['long_ball_accuracy/90'] = resultTwo;
        //result['Through passes'] = resultThree;
        const playerInfor = await playerCtl.find({playerId: playerid})
        const playerFeature = await plyfeaCtl.find({playerId: playerid})
        for (let a of playerInfor){
            for (let b of playerFeature){
                result['playerId'] = parseInt(playerid);
                result['playerName'] = a.playerName;
                result['longPassTotal'] = parseInt(b.long_pass_total);
                result['longPassAccuracy'] = parseFloat(parseFloat(b.long_pass_success_rate).toFixed(2));
                result['longPassAccuracy/90'] = parseFloat((((b['long_pass_success']/b['long_pass_total'] || 0)/b.minutes_played || 0)*90).toFixed(2));
                //console.log(((b['through_ball_success']/b['through_ball_total'])/b.minutes_played)*5400)
            }
        }
        /*for (let a of fea){
            if (a.playerId == playerid){
                result['playerId'] = a.playerId;
                result['long_ball_total'] = parseFloat(((a['long_pass_total']/a.time_played || 0)*90).toFixed());
                result['long_ball_accuracy'] = parseFloat((((a['long_pass_success']/a['long_pass_total'] || 0)/a.time_played || 0)*90).toFixed(2));
                //result['through passes'] = parseFloat((a['Through passes All Match']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }*/
        result['accurate_long_ball'] = longpass_successful;
        result['inaccurate_long_ball'] = longpass_unsuccessful;
        result['longPass'] = longpass;
        result['Figure'] = figure;
        result['Table'] = table;
        ctx.body = result;
    })

    .get('/actions/keypass/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{type_id:0}, {type_id:1}, {type_id:2}, {type_id:4}, {type_id:5}, {type_id:6}, {type_id:7}], playerId: playerid});
        //console.log(r)
        let result = {}
        let keyPass = []; let assist = [];
        let ret1 = {}
        for (let a of r){
            if (a.result_id == 4){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                /*console.log(a.x);
                console.log(a.y);
                console.log(a.end_x);
                console.log(a.end_y);
                console.log(obj);*/
                assist.push(obj) 
            }
            else if (a.result_id == 5){
                let obj = {}
                obj.x1 = (a.x/105*100).toFixed(2);
                obj.y1 = (a.y/68*100).toFixed(2);
                obj.x2 = (a.end_x/105*100).toFixed(2);
                obj.y2 = (a.end_y/68*100).toFixed(2);
                keyPass.push(obj) 
            }
            let ptplayerId = a.passto_playerId;
            if (a.result_id == 4 || a.result_id == 5){
                if(!Object.hasOwnProperty.call(ret1, ptplayerId)){//ret无playerId,tui
                    ret1[ptplayerId] = { playerId: parseInt(ptplayerId), Number: 1, Assist: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret1[ptplayerId].Number = ret1[ptplayerId].Number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
                if (a.result_id == 4){
                    ret1[ptplayerId].Assist = ret1[ptplayerId].Assist + 1;
                }
            }
        }
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        let createchance = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            //obj.teamId = a.teamId;
            //obj.competitionId = a.competitionId;
            //obj.pass_total = parseFloat(((a['long_pass_total']/a.time_played || 0)*90).toFixed());
            obj.pass_success = parseFloat(((a['shot_assist']/a.minutes_played || 0)*90).toFixed(1));
            playerfeatures.push(obj)
            const player = await playerCtl.find({playerId: a.playerId})
            for (let b of player){
                let obj1 = {
                    playerId: a.playerId,
                    playerName: b.playerName,
                    createChanceTotal: parseInt(a.shot_assist),
                    assistRate: parseFloat(parseFloat(a.assists/a['shot_assist'] || 0).toFixed(2))
                }
                createchance.push(obj1);
            }
        }
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf.pass_success != 'none'){
                let pa = pf.pass_success;
                if(!Object.hasOwnProperty.call(ret2, pa)){//ret无playerId,tui
                    ret2[pa] = { sa: pa, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[pa].number = ret2[pa].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = [];let receiver = []; 
        var res1 = Object.keys(ret1).sort(function(a,b){ return ret1[b]["Number"]-ret1[a]["Number"]; });
        for(var key in res1){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            receiver.push(ret1[res1[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["sa"]-ret2[b]["sa"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        //figure['long_ball_total/90'] = resultOne;
        figure['createChance/90'] = resultTwo;
        const playerInfor = await playerCtl.find({playerId: playerid})
        const playerFeature = await plyfeaCtl.find({playerId: playerid})
        for (let a of playerInfor){
            for (let b of playerFeature){
                result['playerId'] = parseInt(playerid);
                result['playerName'] = a.playerName;
                result['createChanceTotal'] = parseInt(b.shot_assist);
                result['assistRate'] = parseFloat(parseFloat(b.assists/b['shot_assist'] || 0).toFixed(2));
                result['createChance/90'] = parseFloat(((b['shot_assist']/b.minutes_played || 0)*90).toFixed(1));
                //console.log(((b['through_ball_success']/b['through_ball_total'])/b.minutes_played)*5400)
            }
        }
        let Receiver = []; let i = 0;
        for (let a of receiver){
            if (i < 3){
                const player = await playerCtl.retrieve(a.playerId)
                //console.log(player)
                obj = {
                    Receiver: player.playerName,
                    shotAssists: a.Number,
                    Assists: a.Assist,
                    Rate: parseFloat((a.Assist/a.Number || 0).toFixed(2))
                }
                Receiver.push(obj);
                i++;
            }
            else{
                break;
            }
        }
        let zuobiao = {}
        zuobiao.keyPass = keyPass;
        zuobiao.assist = assist;
        result.zuoBiao = zuobiao;
        result.createChance = createchance;
        result.Figure = figure;
        result.Table = Receiver;
        ctx.body = result;//到此一游
    })
    
    .get('/actions/rosepass/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({$or:[{eventId:8}], playerId: playerid});
        let result = {}; //let zuobiao = {}; let inaccurate = []; let accurate = []; let acceleration = []; let dribblewon = []; let dribblelost = [];
        let pf = 0; let pfd = 0; pfa = 0; let plf = 0; let plfd = 0; let plfa= 0; let prf = 0; let prfd = 0; let prfa = 0; let pll = 0; let plld = 0; let plla = 0; let prl = 0; let prld = 0; let prla = 0; let plb = 0; let plbd = 0; let plba = 0; let prb = 0; let prbd = 0; let prba = 0; let pb = 0; let pbd = 0; let pba = 0;
        let lf = 0; let lfd = 0; lfa = 0; let llf = 0; let llfd = 0; let llfa= 0; let lrf = 0; let lrfd = 0; let lrfa = 0; let lll = 0; let llld = 0; let llla = 0; let lrl = 0; let lrld = 0; let lrla = 0; let llb = 0; let llbd = 0; let llba = 0; let lrb = 0; let lrbd = 0; let lrba = 0; let lb = 0; let lbd = 0; let lba = 0;
        let rf = 0; let rfd = 0; rfa = 0; let rlf = 0; let rlfd = 0; let rlfa= 0; let rrf = 0; let rrfd = 0; let rrfa = 0; let rll = 0; let rlld = 0; let rlla = 0; let rrl = 0; let rrld = 0; let rrla = 0; let rlb = 0; let rlbd = 0; let rlba = 0; let rrb = 0; let rrbd = 0; let rrba = 0; let rb = 0; let rbd = 0; let rba = 0;
        for (let a of r){
            let i = 0; let x = 0; let y = 0;
            for (let tag of a.tags){
                if (tag.id == 1801){
                    i = 1;
                }
            }
            for (let position of a.positions){
                x = position.x;
                y = position.y;
                break;
            }
            if (x >= 85 && y >= 20 && y <= 80){
                if (a.passType8 == 'forward'){
                    pf++;
                    pfd+=a.eventDistance;
                    if (i == 1){
                        pfa++;
                    }
                }
                else if (a.passType8 == 'left forward'){
                    plf++;
                    plfd+=a.eventDistance;
                    if (i == 1){
                        plfa++;
                    }
                }
                else if (a.passType8 == 'right forward'){
                    prf++;
                    prfd+=a.eventDistance;
                    if (i == 1){
                        prfa++;
                    }
                }
                else if (a.passType8 == 'left lateral'){
                    pll++;
                    plld+=a.eventDistance;
                    if (i == 1){
                        plla++;
                    }
                }
                else if (a.passType8 == 'right lateral'){
                    prl++;
                    prld+=a.eventDistance;
                    if (i == 1){
                        prla++;
                    }
                }
                else if (a.passType8 == 'left back'){
                    plb++;
                    plbd+=a.eventDistance;
                    if (i == 1){
                        plba++;
                    }
                }
                else if (a.passType8 == 'right back'){
                    prb++;
                    prbd+=a.eventDistance;
                    if (i == 1){
                        prba++;
                    }
                }
                else if (a.passType8 == 'back'){
                    pb++;
                    pbd+=a.eventDistance;
                    if (i == 1){
                        pba++;
                    }
                }
            }
            else if ((x > 50 && y > 80 && y <= 100) || (x > 50 && y >= 50 && y <= 100 && x < 85)){
                if (a.passType8 == 'forward'){
                    rf++;
                    rfd+=a.eventDistance;
                    if (i == 1){
                        rfa++;
                    }
                }
                else if (a.passType8 == 'left forward'){
                    rlf++;
                    rlfd+=a.eventDistance;
                    if (i == 1){
                        rlfa++;
                    }
                }
                else if (a.passType8 == 'right forward'){
                    rrf++;
                    rrfd+=a.eventDistance;
                    if (i == 1){
                        rrfa++;
                    }
                }
                else if (a.passType8 == 'left lateral'){
                    rll++;
                    rlld+=a.eventDistance;
                    if (i == 1){
                        rlla++;
                    }
                }
                else if (a.passType8 == 'right lateral'){
                    rrl++;
                    rrld+=a.eventDistance;
                    if (i == 1){
                        rrla++;
                    }
                }
                else if (a.passType8 == 'left back'){
                    rlb++;
                    rlbd+=a.eventDistance;
                    if (i == 1){
                        rlba++;
                    }
                }
                else if (a.passType8 == 'right back'){
                    rrb++;
                    rrbd+=a.eventDistance;
                    if (i == 1){
                        rrba++;
                    }
                }
                else if (a.passType8 == 'back'){
                    rb++;
                    rbd+=a.eventDistance;
                    if (i == 1){
                        rba++;
                    }
                }
            }
            else if ((x > 50 && y >= 0 && y < 20) || (x > 50 && y >= 0 && y < 50 && x < 85)){
                if (a.passType8 == 'forward'){
                    lf++;
                    lfd+=a.eventDistance;
                    if (i == 1){
                        lfa++;
                    }
                }
                else if (a.passType8 == 'left forward'){
                    llf++;
                    llfd+=a.eventDistance;
                    if (i == 1){
                        llfa++;
                    }
                }
                else if (a.passType8 == 'right forward'){
                    lrf++;
                    lrfd+=a.eventDistance;
                    if (i == 1){
                        lrfa++;
                    }
                }
                else if (a.passType8 == 'left lateral'){
                    lll++;
                    llld+=a.eventDistance;
                    if (i == 1){
                        llla++;
                    }
                }
                else if (a.passType8 == 'right lateral'){
                    lrl++;
                    lrld+=a.eventDistance;
                    if (i == 1){
                        lrla++;
                    }
                }
                else if (a.passType8 == 'left back'){
                    llb++;
                    llbd+=a.eventDistance;
                    if (i == 1){
                        llba++;
                    }
                }
                else if (a.passType8 == 'right back'){
                    lrb++;
                    lrbd+=a.eventDistance;
                    if (i == 1){
                        lrba++;
                    }
                }
                else if (a.passType8 == 'back'){
                    lb++;
                    lbd+=a.eventDistance;
                    if (i == 1){
                        lba++;
                    }
                }
            }
            else {continue;}
        }
        let Left = [
            {
                Name: 'forward',
                Distance: ((lfd/lf || 0)).toFixed(2),
                Accuracy: ((lfa/lf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left forward',
                Distance: ((llfd/llf || 0)).toFixed(2),
                Accuracy: ((llfa/llf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right forward',
                Distance: ((lrfd/lrf || 0)).toFixed(2),
                Accuracy: ((lrfa/lrf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left lateral',
                Distance: ((llld/lll || 0)).toFixed(2),
                Accuracy: ((llla/lll || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right lateral',
                Distance: ((lrld/lrl || 0)).toFixed(2),
                Accuracy: ((lrla/lrl || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'back',
                Distance: ((lbd/lb || 0)).toFixed(2),
                Accuracy: ((lba/lb || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left back',
                Distance: ((llbd/llb || 0)).toFixed(2),
                Accuracy: ((llba/llb || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right back',
                Distance: ((lrbd/lrb || 0)).toFixed(2),
                Accuracy: ((lrba/lrb || 0)*100).toFixed(2) + '%'
            }
        ]
        let Right = [
            {
                Name: 'forward',
                Distance: ((rfd/rf || 0)).toFixed(2),
                Accuracy: ((rfa/rf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left forward',
                Distance: ((rlfd/rlf || 0)).toFixed(2),
                Accuracy: ((rlfa/rlf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right forward',
                Distance: ((rrfd/rrf || 0)).toFixed(2),
                Accuracy: ((rrfa/rrf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left lateral',
                Distance: ((rlld/rll || 0)).toFixed(2),
                Accuracy: ((rlla/rll || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right lateral',
                Distance: ((rrld/rrl || 0)).toFixed(2),
                Accuracy: ((rrla/rrl || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'back',
                Distance: ((rbd/rb || 0)).toFixed(2),
                Accuracy: ((rba/rb || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left back',
                Distance: ((rlbd/rlb || 0)).toFixed(2),
                Accuracy: ((rlba/rlb || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right back',
                Distance: ((rrbd/rrb || 0)).toFixed(2),
                Accuracy: ((rrba/rrb || 0)*100).toFixed(2) + '%'
            }
        ]
        let Penalty = [
            {
                Name: 'forward',
                Distance: ((pfd/pf || 0)).toFixed(2),
                Accuracy: ((pfa/pf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left forward',
                Distance: ((plfd/plf || 0)).toFixed(2),
                Accuracy: ((plfa/plf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right forward',
                Distance: ((prfd/prf || 0)).toFixed(2),
                Accuracy: ((prfa/prf || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left lateral',
                Distance: ((plld/pll || 0)).toFixed(2),
                Accuracy: ((plla/pll || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right lateral',
                Distance: ((prld/prl || 0)).toFixed(2),
                Accuracy: ((prla/prl || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'back',
                Distance: ((pbd/pb || 0)).toFixed(2),
                Accuracy: ((pba/pb || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'left back',
                Distance: ((plbd/plb || 0)).toFixed(2),
                Accuracy: ((plba/plb || 0)*100).toFixed(2) + '%'
            },
            {
                Name: 'right back',
                Distance: ((prbd/prb || 0)).toFixed(2),
                Accuracy: ((prba/prb || 0)*100).toFixed(2) + '%'
            }
        ]
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Passes'] = parseFloat((a['Passes All Match']/a.timePlayed*90).toFixed());
            obj['Pass accuracy'] = parseFloat(((a['Passes All Match Accuracy']/a['Passes All Match'] || 0)*100).toFixed());
            obj['xGChain'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
            obj['xGBuildup'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
            obj['Forward passes'] = parseFloat((a['Forward passes All Match']/a.timePlayed*90).toFixed());
            obj['Passes to final third'] = parseFloat((a['Passes to final third All Match']/a.timePlayed*90).toFixed());
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['xGChain'] != 'none'){
                let xGChain = pf['xGChain'];
                if(!Object.hasOwnProperty.call(ret2, xGChain)){//ret无playerId,tui
                    ret2[xGChain] = { xGChain, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[xGChain].number = ret2[xGChain].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['xGBuildup'] != 'none'){
                let xGBuildup = pf['xGBuildup'];
                if(!Object.hasOwnProperty.call(ret3, xGBuildup)){//ret无playerId,tui
                    ret3[xGBuildup] = { xGBuildup, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[xGBuildup].number = ret3[xGBuildup].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret4 = {};
        for( let pf of playerfeatures){
            if (pf['Passes'] != 'none'){
                let Passes = pf['Passes'];
                if(!Object.hasOwnProperty.call(ret4, Passes)){//ret无playerId,tui
                    ret4[Passes] = { Passes, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret4[Passes].number = ret4[Passes].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret5 = {};
        for( let pf of playerfeatures){
            if (pf['Pass accuracy'] != 'null'){
                let pa = pf['Pass accuracy'];
                if(!Object.hasOwnProperty.call(ret5, pa)){//ret无playerId,tui
                    ret5[pa] = { pa, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret5[pa].number = ret5[pa].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret6 = {};
        for( let pf of playerfeatures){
            if (pf['Forward passes'] != 'none'){
                let fp = pf['Forward passes'];
                if(!Object.hasOwnProperty.call(ret6, fp)){//ret无playerId,tui
                    ret6[fp] = { fp, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret6[fp].number = ret6[fp].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret7 = {};
        for( let pf of playerfeatures){
            if (pf['Passes to final third'] != 'none'){
                let pft = pf['Passes to final third'];
                if(!Object.hasOwnProperty.call(ret7, pft)){//ret无playerId,tui
                    ret7[pft] = { pft, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret7[pft].number = ret7[pft].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = []; let resultFour = []; let resultFive = []; let resultSix = []; let resultSeven = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["xGChain"]-ret2[b]["xGChain"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["xGBuildup"]-ret3[b]["xGBuildup"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res4 = Object.keys(ret4).sort(function(a,b){ return ret4[a]["Passes"]-ret4[b]["Passes"]; });
        for(var key in res4){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultFour.push(ret4[res4[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res5 = Object.keys(ret5).sort(function(a,b){ return ret5[a]["pa"]-ret5[b]["pa"]; });
        for(var key in res5){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultFive.push(ret5[res5[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res6 = Object.keys(ret6).sort(function(a,b){ return ret6[a]["fp"]-ret6[b]["fp"]; });
        for(var key in res6){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultSix.push(ret6[res6[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res7 = Object.keys(ret7).sort(function(a,b){ return ret7[a]["pft"]-ret7[b]["pft"]; });
        for(var key in res7){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultSeven.push(ret7[res7[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        //for (let a of resultFive){
            //a.pa = a.pa + '%';
        //}
        let figure = {};
        figure['Passes'] = resultFour;
        figure['Pass accuracy'] = resultFive;
        figure['xGChain'] = resultTwo;
        figure['xGBuildup'] = resultThree;
        figure['Forward passes'] = resultSix;
        figure['Passes to final third'] = resultSeven;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['passes'] = parseFloat((a['Passes All Match']/a.timePlayed*90).toFixed());
                figure['pass accuracy'] = parseFloat(((a['Passes All Match Accuracy']/a['Passes All Match'] || 0)*100).toFixed());
                figure['xgChain'] = parseFloat((a['Recoveries in final third']/a.timePlayed*90).toFixed(1));
                figure['xgBuildup'] = parseFloat((a['Dribbles in final third All Match Accuracy']/a.timePlayed*90).toFixed(1));
                figure['forward passes'] = parseFloat((a['Forward passes All Match']/a.timePlayed*90).toFixed());
                figure['passes to final third'] = parseFloat((a['Passes to final third All Match']/a.timePlayed*90).toFixed());
            }
            else {continue;}
        }
        /**zuobiao['Inaccurate pass'] = inaccurate;
        zuobiao['Accurate pass'] = accurate;
        zuobiao.Acceleration = acceleration;
        zuobiao['Won dribble'] = dribblewon;
        zuobiao['Lost dribble'] = dribblelost;
        zuobiao.Shot = shot;
        result.zuobiao = zuobiao;*/
        result.Left = Left;
        result.Right = Right;
        result.Penalty = Penalty;
        result.Figure = figure;
        ctx.body = result;
    })

    .get('/actions/progression/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({playerId:playerid});
        let result = {}; result['Progressive pass'] = []; result['Progressive run'] = [];
        let p1 = 0; let p11 =0; p2 = 0; let p21 =0; p3 = 0; let p31 =0; p4 = 0; let p41 =0;
        let t2 = 0; let pl = 0; let pap = 0; let ps = 0; let pg = 0; let pa = 0;
        for (let a of r){
            let i = 0;
            for (let tag of a.tags){
                if (tag.id == 1801){
                    i =1;
                }
                else {continue;}
            }
            if (a.progression == 'progression pass'){
                let obj = {}; let z = 0;// let i = 0; let h = 0; let j = 0; let k = 0; let l = 0;
                //obj.x = a.startX;
                //obj.y = a.startY;
                for(let position of a.positions){
                    z++;
                    if (z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y;
                    }
                    else{continue;}
                }
                result['Progressive pass'].push(obj);
                if (a.eventDistance >= 0 && a.eventDistance < 20){
                    p1++;
                    if (i == 1){
                        p11++;
                    }
                }
                else if (a.eventDistance >= 20 && a.eventDistance < 30){
                    p2++;
                    if (i == 1){
                        p21++;
                    }
                }
                else if (a.eventDistance >= 30 && a.eventDistance < 40){
                    p3++;
                    if (i == 1){
                        p31++;
                    }
                }
                else if (a.eventDistance >= 40){
                    p4++;
                    if (i == 1){
                        p41++;
                    }
                }
                else{continue;}
            }
            else if (a.progression == 'progression run'){
                t2++;
                let obj = {}; let z = 0; let h = 0; let j = 0; let k = 0; let l = 0;
                //obj.x = a.startX;
                //obj.y = a.startY;
                for(let position of a.positions){
                    z++;
                    if (z == 1){
                        obj.x1 = position.x;
                        obj.y1 = position.y;
                    }
                    else if (z == 2){
                        obj.x2 = position.x;
                        obj.y2 = position.y;
                    }
                    else{continue;}
                }
                result['Progressive run'].push(obj);
                const events = await eventCtl.find({eventId: a.eventAfterId, eventSec: a.eventAfterTime, matchId: a.matchId});
                for (let event of events){
                    for (let tag1 of event.tags){
                        if (tag1.id == 1801){
                            h = 1;
                        }
                        else if (tag1.id == 702 || tag1.id == 703){
                            j = 1;
                        }
                        else if (tag1.id == 101){
                            k = 1;
                        }
                        else if (tag1.id == 301){
                            l = 1;
                        }
                        else {continue;}
                    }
                    if ((event.eventId == 1 && j == 0) || (event.eventId == 8 && h == 0) || (event.subEventId == 32 && h == 0) || (event.subEventId == 36 && h == 0) || (event.subEventId == 80 && h == 0)){
                        pl++;
                    }
                    else if ((event.eventId == 8 && h == 1) || (event.subEventId == 32 && h == 1) ||(event.subEventId == 36 && h == 1) || (event.subEventId == 80 && h == 1)){
                        pap++;
                    }
                    else if (event.eventId == 10 || event.subEventId == 33 || event.subEventId == 35){
                        ps++;
                    }
                    else if (k == 1){
                        pg++;
                    }
                    else if (l == 1){
                        pa++;
                    }
                    else {continue;}
                }
            }
            else {continue;}
        }
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Progressive passes'] = parseFloat((a['Progressive Passes']/a.timePlayed*90).toFixed());
            obj['Progressive runs'] = parseFloat((a['Progressive Runs']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Progressive passes'] != 'none'){
                let PP = pf['Progressive passes'];
                if(!Object.hasOwnProperty.call(ret2, PP)){//ret无playerId,tui
                    ret2[PP] = { PP, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[PP].number = ret2[PP].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Progressive runs'] != 'none'){
                let PR = pf['Progressive runs'];
                if(!Object.hasOwnProperty.call(ret3, PR)){//ret无playerId,tui
                    ret3[PR] = { PR, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[PR].number = ret3[PR].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]['PP']-ret2[b]['PP']; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]['PR']-ret3[b]['PR']; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Progressive passes'] = resultTwo;
        figure['Progressive runs'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['progressive passes'] = parseFloat((a['Progressive Passes']/a.timePlayed*90).toFixed());
                figure['progressive runs'] = parseFloat((a['Progressive Runs']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        table1 = [
            { Distance: '0-20m', 'Prog.passes': p1, accurate: p11, rate:((p11/p1 || 0)*100).toFixed()+'%' },
            { Distance: '20-30m', 'Prog.passes': p2, accurate: p21, rate:((p21/p2 || 0)*100).toFixed()+'%' },
            { Distance: '30-40m', 'Prog.passes': p3, accurate: p31, rate:((p31/p3 || 0)*100).toFixed()+'%' },
            { Distance: '40m+', 'Prog.passes': p4, accurate: p41, rate:((p41/p4 || 0)*100).toFixed()+'%' },
            { Distance: 'Total', 'Prog.passes': p1+p2+p3+p4, accurate: p11+p21+p31+p41, rate:(((p11+p21+p31+p41)/(p1+p2+p3+p4) || 0)*100).toFixed()+'%' }
        ];
        table2 = [
            { 'Events after prog. runs': 'Loss', rate:((pl/t2 || 0)*100).toFixed()+'%' },
            { 'Events after prog. runs': 'Accurate pass', rate:((pap/t2 || 0)*100).toFixed()+'%' },
            { 'Events after prog. runs': 'Shot', rate:((ps/t2 || 0)*100).toFixed()+'%' },
            { 'Events after prog. runs': 'Goal', rate:((pg/t2 || 0)*100).toFixed()+'%' },
            { 'Events after prog. runs': 'Assist', rate:((pa/t2 || 0)*100).toFixed()+'%' }
        ];
        result.Figure = figure;
        result.Table1 = table1;
        result.Table2 = table2;
        ctx.body = result;
    })

    .get('/actions/dribbles/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r = await eventCtl.find({eventId: 1,playerId:playerid});
        let result = {}; let zuobiao = {}; let keptpossession = []; let followbyshot = []; let followbygoal = [];
        let fd = 0, fk = 0, fs = 0, fso = 0, fg = 0, fxg = 0;
        let md = 0, mk = 0, ms = 0, mso = 0, mg = 0, mxg = 0;
        let dd = 0, dk = 0, ds = 0, dso = 0, dg = 0, dxg = 0;
        let gd = 0, gk = 0, gs = 0, gso = 0, gg = 0, gxg = 0;
        for (let a of r){
            let obj = {}; let z = 0; let i = 0; let h = 0; let j = 0; let k = 0; let l = 0;
            //obj.x = a.startX;
            //obj.y = a.startY;
            for(let position of a.positions){
                z++;
                if (z == 1){
                    obj.x = position.x;
                    obj.y = position.y;
                }
                else{continue;}
            }
            const pp = await playerCtl.retrieve(a.duelAgainst)
            for (let key of Object.keys(pp.role)){
                let roles = pp.role[key]
                if (key == 'code2'){
                    role = roles;
                }
                else {continue;}
            } 
            for (let tag of a.tags){
                if (tag.id == 501 || tag.id == 502 || tag.id == 503 || tag.id == 504){
                    i = 1;
                }
                else if (tag.id == 1801){
                    h = 1;
                }
                else {continue;}
            }
            if (i == 1){
                if (role == 'FW'){
                    fd++;
                    fxg+=a.xG;
                }
                else if (role == 'MD'){
                    md++;
                    mxg+=a.xG;
                }
                else if (role == 'DF'){
                    dd++;
                    dxg+=a.xG;
                }
                else if (role == 'GK'){
                    gd++;
                    gxg+=a.xG;
                }
                else {continue;}
            }
            if (a.eventAfterId == 10 || a.eventAfterId == 3){
                j = 1;
                const r1 = await eventCtl.find({eventId: a.eventAfterId, eventSec: a.eventAfterTime, matchId: a.matchId});
                for (let b of r1){
                    for (let tag1 of b.tags){
                        if (tag1.id == 101){
                            k = 1;
                        }
                        else if (tag1.id == 1801){
                            l = 1;
                        }
                        else {continue;}
                    }
                }
            }
            if (i == 1 && h == 1 && j == 0 && k==0){
                keptpossession.push(obj);
                if (role == 'FW'){
                    fk++;
                }
                else if (role == 'MD'){
                    mk++;
                }
                else if (role == 'DF'){
                    dk++;
                }
                else if (role == 'GK'){
                    gk++;
                }
                else {continue;}
            }
            else if (i == 1 && h == 1 && j == 1 && k==0){
                followbyshot.push(obj);
                if (role == 'FW'){
                    fs++;
                }
                else if (role == 'MD'){
                    ms++;
                }
                else if (role == 'DF'){
                    ds++;
                }
                else if (role == 'GK'){
                    gs++;
                }
                else {continue;}
                if (l == 1){
                    if (role == 'FW'){
                        fso++;
                    }
                    else if (role == 'MD'){
                        mso++;
                    }
                    else if (role == 'DF'){
                        dso++;
                    }
                    else if (role == 'GK'){
                        gso++;
                    }
                    else {continue;}
                }
            }
            else if (i == 1 && h == 1 && j == 1 && k==1){
                followbygoal.push(obj);
                if (role == 'FW'){
                    fg++;
                }
                else if (role == 'MD'){
                    mg++;
                }
                else if (role == 'DF'){
                    dg++;
                }
                else if (role == 'GK'){
                    gg++;
                }
                else {continue;}
            }
            else {continue;}
        }
        let table = []; let forward = {}; let midfielder = {}; let defender = {}; let goalkeeper = {}; let total = {};
        forward['Opponent position'] = 'FW'; forward.Dribbles = fd; forward['kept possession'] = fk; forward.rate = ((fk/fd || 0)*100).toFixed()+'%'; forward['Shots_after'] = fs; forward['on target'] = fso; forward.xG = fxg; forward['Goals after'] = fg; table.push(forward);
        midfielder['Opponent position'] = 'MD'; midfielder.Dribbles = md; midfielder['kept possession'] = mk; midfielder.rate = ((mk/md || 0)*100).toFixed()+'%'; midfielder['Shots_after'] = ms; midfielder['on target'] = mso; midfielder.xG = mxg; midfielder['Goals after'] = mg; table.push(midfielder);
        defender['Opponent position'] = 'DF'; defender.Dribbles = dd; defender['kept possession'] = dk; defender.rate = ((dk/dd || 0)*100).toFixed()+'%'; defender['Shots_after'] = ds; defender['on target'] = dso; defender.xG = dxg; defender['Goals after'] = dg; table.push(defender);
        goalkeeper['Opponent position'] = 'GK'; goalkeeper.Dribbles = gd; goalkeeper['kept possession'] = gk; goalkeeper.rate = ((gk/gd || 0)*100).toFixed()+'%'; goalkeeper['Shots_after'] = gs; goalkeeper['on target'] = gso; goalkeeper.xG = gxg; goalkeeper['Goals after'] = gg; table.push(goalkeeper);
        total['Opponent position'] = 'Total'; total.Dribbles = fd+md+dd+gd; total['kept possession'] = fk+mk+dk+gk; total.rate = ((total['kept possession']/total.Dribbles || 0)*100).toFixed()+'%'; total['Shots_after'] = fs+ms+ds+gs; total['on target'] = fso+mso+dso+gso; total.xG = fxg+mxg+dxg+gxg; total['Goals after'] = fg+mg+dg+gg; table.push(total);
        const fea = await plyfeaCtl.list();
        let playerfeatures = []
        for (let a of fea){
            let obj = {}
            obj.playerId = a.playerId;
            obj.teamId = a.teamId;
            obj.competitionId = a.competitionId;
            obj['Dribbles'] = parseFloat((a['Dribbles All Match']/a.timePlayed*90).toFixed(1));
            obj['Successful dribbles'] = parseFloat((a['Dribbles All Match Accuracy']/a.timePlayed*90).toFixed(1));
            playerfeatures.push(obj)
        }
        //console.log(playerfeatures)
        let ret2 = {};
        for( let pf of playerfeatures){
            if (pf['Dribbles'] != 'none'){
                let Dribbles = pf['Dribbles'];
                if(!Object.hasOwnProperty.call(ret2, Dribbles)){//ret无playerId,tui
                    ret2[Dribbles] = { Dribbles, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret2[Dribbles].number = ret2[Dribbles].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let ret3 = {};
        for( let pf of playerfeatures){
            if (pf['Successful dribbles'] != 'none'){
                let sd = pf['Successful dribbles'];
                if(!Object.hasOwnProperty.call(ret3, sd)){//ret无playerId,tui
                    ret3[sd] = { sd, number: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                }else{//ret有playerId,tui 对应数值
                    ret3[sd].number = ret3[sd].number + 1; 
                    //ret[playerId].fxg = fg.fxg;
                    //ret[playerId].fyg = fg.fyg;
                }
            }
            else{continue;}
        }
        let resultTwo = []; let resultThree = [];
        var res2 = Object.keys(ret2).sort(function(a,b){ return ret2[a]["Dribbles"]-ret2[b]["Dribbles"]; });
        for(var key in res2){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultTwo.push(ret2[res2[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        var res3 = Object.keys(ret3).sort(function(a,b){ return ret3[a]["sd"]-ret3[b]["sd"]; });
        for(var key in res3){
            //console.log(result[res2[key]]);
            //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
            resultThree.push(ret3[res3[key]])
          //console.log("key: " + res2[key] + " ,value: " + result[res2[key]]);
        }
        let figure = {};
        figure['Dribbles'] = resultTwo;
        figure['Successful dribbles'] = resultThree;
        for (let a of fea){
            if (a.playerId == playerid){
                figure.playerId = a.playerId;
                figure['dribbles'] = parseFloat((a['Dribbles All Match']/a.timePlayed*90).toFixed(1));
                figure['successful dribbles'] = parseFloat((a['Dribbles All Match Accuracy']/a.timePlayed*90).toFixed(1));
            }
            else {continue;}
        }
        zuobiao['Kept possession'] = keptpossession;
        zuobiao['Followed by a shot'] = followbyshot;
        zuobiao['Followed by a goal'] = followbygoal;
        result.zuobiao = zuobiao;
        result.Figure = figure;
        result.Table = table;
        ctx.body = result;
    })

    .get('/tables/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const matches = await MplCtl.find({playerId:playerid});
        //console.log(matches)
        let result = [];
        for (let a of matches){
            let obj = {}; let h = 0; let i = 0; let g = 0; let j = 0; let k = 0; let l = 0; let xg = 0;
            const match = await matchCtl.retrieve(a.matchId)
            //console.log(match)
            obj.Match = match.label;
            obj.Date = (match.dateutc).substring(0,10);
            obj['Minutes played'] = a.playTime;
            obj['Total actions'] = a.Actions.allMatch;
            obj['Total actions successful'] = a.Actions.allMatchAcc;
            obj['actionsuccessful rate'] = a.Actions.allRate;
            const events = await eventCtl.find({playerId: playerid, matchId: a.matchId});
            for (let b of events){
                if (b.subEventId == 10){
                    g++;
                }
                for (let tag of b.tags){
                    if (tag.id == 101){
                        h++;
                    }
                    else if (tag.id == 301){
                        i++;
                    }
                    else if (tag.id == 1701){
                        j++;
                    }
                    else if (tag.id == 1702){
                        k++;
                    }
                    else if (b.subEventId == 10 && tag.id == 703){
                        l++;
                    }
                    else {continue;}
                }
                xg+=b.xG;
            }
            obj.Goals = h;
            obj.Assists = i;
            obj.Shots = a.Shots.allMatch;
            obj['on target'] = a.Shots.allMatchAcc;
            obj['ontarget rate'] = a.Shots.allRate;
            obj.xG = xg.toFixed(2);
            obj.Passes = a.Passes.allMatch;
            obj['Passes accurate'] = a.Passes.allMatchAcc;
            obj['Passaccurate rate']= a.Passes.allRate;
            obj.Crosses = a.Crosses.allMatch;
            obj['Crosses accurate'] = a.Crosses.allMatchAcc;
            obj['Crossaccurate rate']= a.Crosses.allRate;
            obj.Dribbles = a.Dribbles.allMatch;
            obj['Dribbles successful'] = a.Dribbles.allMatchAcc;
            obj['Dribblesuccessful rate']= a.Dribbles.allRate;
            obj.Duels = a.Duels.allMatch;
            obj['Duels won'] = a.Duels.allMatchAcc;
            obj['Duelwon rate']= a.Duels.allRate;
            obj['Aerial duels'] = g;
            obj['Aerial duels won'] = l;
            obj['Aerialduelwon rate']= ((l/g || 0)*100).toFixed()+'%';
            obj['Yellow cards'] = k;
            obj['Red cards'] = j;
            result.push(obj);
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        var objectArraySort = function (keyname) {
            return function (objectN, objectM){
                var valueN = objectN[keyname]
                var valueM = objectM[keyname]
                if (valueN < valueM) return 1
                else if  (valueN > valueM) return -1
                else return 0
            }
        }
        result = result.sort(objectArraySort('Date'));
        ctx.body = result;
    })

    .get('/shotassists/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r1 = await eventCtl.find({playerId:playerid});
        const r2 = await eventCtl.find({eventId:10});
        const r3 = await eventCtl.find({$or:[{eventId:8},{eventId:3}]});
        //const r4 = await eventCtl.find({eventId:8, playerId:playerid});
        //const r5 = await eventCtl.find({eventId:3, playerId:playerid});
        //console.log(r2)
        /**let r3 = [];
        for (let a of r4){
            r3.push(a);
        }
        for (let a of r5){
            r3.push(a);
        }*/
        //console.log(r3)
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        //r2 = r2.sort(compare1('eventSec'));
        //r3 = r3.sort(compare1('eventSec'));
        //console.log(r3)
        let result = {}; let zuobiao = {}; zuobiao.Assist = [];
        for (let a of r1){
            for (let tag of a.tags){
                if (tag.id == 301){
                    let obj = {}; let i = 0; 
                    //obj.x = a.startX;
                    //obj.y = a.startY;
                    for(let position of a.positions ){
                        i++;
                        if (i == 1){
                            obj.x1 = position.x;
                            obj.y1 = position.y;
                        }
                        else if (i == 2){
                            obj.x2 = position.x;
                            obj.y2 = position.y;
                        }
                        else{continue;}
                    }
                    //obj.eventId = a.eventId;
                    //obj.subeventId = a.subEventId;
                    zuobiao.Assist.push(obj);
                }
                else {continue;}
            }
        }
        /**function binary_search(arr, key) {
            var low = 0,
                high = arr.length - 1;
         
            while(low <= high) {
                var mid = parseInt((high + low) /2);
                  // console.log(mid+'h'+high+'l'+low);
                if(key == arr[mid]) {
                    return mid;
                } else if(key > arr[mid]) {
                    low = mid + 1;
                } else {
                    high = mid -1;
                }
            }
            return -1
        }*/
        let ret = {}; let shotassists = []
        for (let a of r2){
            let time = []; let z = 0; let time1 = [];
            for (let b of r3){
                if(b.eventSec < a.eventSec && b.matchId == a.matchId){
                    time.push(b);
                    //time1.push(b);
                }
                //else if (b.eventSec >= a.eventSec) {break;}
                else {continue;}
            }
            //const time = await eventCtl.findtime({$or:[{eventId:8},{eventId:3}], matchId: a.matchId, eventSec: {$lt: a.eventSec}});
            //for (let event of r3){
                //time.push(event)
            //}
            //const r5 = await eventCtl.find({eventId:3});
            //if (time.length == 0){z = 1;}
            //console.log(z);
            //console.log(time)
            if (time.length != 0){
                time = time.sort(compare('eventSec'));
                //time1 = time1.sort(compare('eventSec'));
                for (let c of time){
                    let t = c.eventSec
                    for (let d of time){
                        if (d.eventSec == t && c.playerId == playerid){// && (c.eventId == 8 || c.eventId == 3)){
                            let playerId = a.playerId; let i = 0
                            if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                                ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                            }else{//ret有playerId,tui 对应数值
                                ret[playerId]['Shot assists'] = ret[playerId]['Shot assists'] + 1; 
                                //ret[playerId].fxg = fg.fxg;
                                //ret[playerId].fyg = fg.fyg;
                            }
                            for (let tag of d.tags){
                                if (tag.id == 301){
                                    i = 1;
                                }
                                else {continue;}
                            }
                            if (i == 0){
                                let obj = {}; let i = 0; 
                                //obj.x = a.startX;
                                //obj.y = a.startY;
                                for(let position of d.positions ){
                                    i++;
                                    if (i == 1){
                                        obj.x1 = position.x;
                                        obj.y1 = position.y;
                                    }
                                    if (i == 2){
                                        obj.x2 = position.x;
                                        obj.y2 = position.y;
                                    }
                                }
                                shotassists.push(obj);
                            }
                            else {
                                if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                                    ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                                }else{//ret有playerId,tui 对应数值 
                                    ret[playerId].Assists = ret[playerId].Assists + 1;
                                    //ret[playerId].fxg = fg.fxg;
                                    //ret[playerId].fyg = fg.fyg;
                                }
                            }
                            //console.log(ret)
                        }
                        else if (d.eventSec < t) {break;}
                        else {continue;}
                    }
                    break;
                }
            }
            else {continue;}
        }
        //console.log(ret)
        zuobiao['Shot assist'] = shotassists; let table = [];
        for (let key of Object.keys(ret)){
            let player = ret[key];
            table.push(player);
        }
        table = table.sort(compare('Assists'));
        //console.log(table)
        let Table = []
        for (let a of table){
            const player = await playerCtl.retrieve(a.playerId)
            //console.log(player)
            obj = {
                Receiver: player.shortName,
                'Shot assists': a['Shot assists'],
                xA: 0,
                Assists: a.Assists
            }
            Table.push(obj);
        }
        //console.log(table)
        result.zuobiao = zuobiao;
        result.table = Table;
        ctx.body = result;
    })
    .get('/shotassist/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const r1 = await eventCtl.find({playerId:playerid});
        const r2 = await eventCtl.find({eventId:10});
        const r3 = await eventCtl.find({$or:[{eventId:8},{eventId:3}], playerId: playerid});
        //const r4 = await eventCtl.find({eventId:8, playerId:playerid});
        //const r5 = await eventCtl.find({eventId:3, playerId:playerid});
        //console.log(r2)
        /**let r3 = [];
        for (let a of r4){
            r3.push(a);
        }
        for (let a of r5){
            r3.push(a);
        }*/
        //console.log(r3)
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        //r2 = r2.sort(compare1('eventSec'));
        //r3 = r3.sort(compare1('eventSec'));
        //console.log(r3)
        let result = {}; let zuobiao = {}; zuobiao.Assist = [];
        for (let a of r1){
            for (let tag of a.tags){
                if (tag.id == 301){
                    let obj = {}; let i = 0; 
                    //obj.x = a.startX;
                    //obj.y = a.startY;
                    for(let position of a.positions ){
                        i++;
                        if (i == 1){
                            obj.x1 = position.x;
                            obj.y1 = position.y;
                        }
                        else if (i == 2){
                            obj.x2 = position.x;
                            obj.y2 = position.y;
                        }
                        else{continue;}
                    }
                    //obj.eventId = a.eventId;
                    //obj.subeventId = a.subEventId;
                    zuobiao.Assist.push(obj);
                }
                else {continue;}
            }
        }
        /**function binary_search(arr, key) {
            var low = 0,
                high = arr.length - 1;
         
            while(low <= high) {
                var mid = parseInt((high + low) /2);
                  // console.log(mid+'h'+high+'l'+low);
                if(key == arr[mid]) {
                    return mid;
                } else if(key > arr[mid]) {
                    low = mid + 1;
                } else {
                    high = mid -1;
                }
            }
            return -1
        }*/
        let ret = {}; let shotassists = []
        for (let a of r2){
            let time = []; let z = 0;
            for (let b of r3){
                if(b.eventSec < a.eventSec && b.matchId == a.matchId && b.eventSec >= a.eventSec-3 && b.matchPeriod == a.matchPeriod){
                    time.push(b);
                    //time1.push(b);
                }
                //else if (b.eventSec >= a.eventSec) {break;}
                else {continue;}
            }
            //const time = await eventCtl.findtime({$or:[{eventId:8},{eventId:3}], matchId: a.matchId, eventSec: {$lt: a.eventSec}});
            //for (let event of r3){
                //time.push(event)
            //}
            //const r5 = await eventCtl.find({eventId:3});
            //if (time.length == 0){z = 1;}
            //console.log(z);
            //console.log(time)
            if (time.length != 0){
                time = time.sort(compare('eventSec'));
                //time1 = time1.sort(compare('eventSec'));
                for (let c of time){
                    let t = c.eventSec
                    for (let d of time){
                        if (d.eventSec == t && a.playerId != playerid){//&& c.playerId == playerid){// && (c.eventId == 8 || c.eventId == 3)){
                            let playerId = a.playerId; let i = 0; //let teamId = a.teamId;
                            if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                                ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 0}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                            }else{//ret有playerId,tui 对应数值
                                ret[playerId]['Shot assists'] = ret[playerId]['Shot assists'] + 1; 
                                //ret[playerId].fxg = fg.fxg;
                                //ret[playerId].fyg = fg.fyg;
                            }
                            for (let tag of d.tags){
                                if (tag.id == 301){
                                    i = 1;
                                }
                                else {continue;}
                            }
                            if (i == 0){
                                let obj = {}; let i = 0; 
                                //obj.x = a.startX;
                                //obj.y = a.startY;
                                for(let position of d.positions ){
                                    i++;
                                    if (i == 1){
                                        obj.x1 = position.x;
                                        obj.y1 = position.y;
                                    }
                                    if (i == 2){
                                        obj.x2 = position.x;
                                        obj.y2 = position.y;
                                    }
                                }
                                shotassists.push(obj);
                            }
                            else {
                                if(!Object.hasOwnProperty.call(ret, playerId)){//ret无playerId,tui
                                    ret[playerId] = { playerId, 'Shot assists': 1, xA: 0, Assists: 1}//, fxg: fg.fxg, fyg: fg.fyg, txg: 0, tyg: 0};本来用来计算按传出和传给的球员算平均坐标
                                }else{//ret有playerId,tui 对应数值 
                                    ret[playerId].Assists = ret[playerId].Assists + 1;
                                    //ret[playerId].fxg = fg.fxg;
                                    //ret[playerId].fyg = fg.fyg;
                                }
                            }
                            //console.log(ret)
                        }
                        else if (d.eventSec < t) {break;}
                        else {continue;}
                    }
                    break;
                }
            }
            else {continue;}
        }
        //console.log(ret)
        zuobiao['Shot assist'] = shotassists; let table = [];
        for (let key of Object.keys(ret)){
            let player = ret[key];
            table.push(player);
        }
        table = table.sort(compare('Assists'));
        //console.log(table)
        let Table = []
        for (let a of table){
            const player = await playerCtl.retrieve(a.playerId)
            //console.log(player)
            obj = {
                Receiver: player.shortName,
                team: player.currentNationalTeamId,
                'Shot assists': a['Shot assists'],
                xA: 0,
                Assists: a.Assists
            }
            Table.push(obj);
        }
        //console.log(table)
        result.zuobiao = zuobiao;
        result.table = Table;
        ctx.body = result;
    })
module.exports = router;

/**
 * @swagger
 * resourcePath: /api
 * description: All about API
 * definitions:
 *   player:
 *     type: "object"
 *     required:
 *       - "name"
 *     properties:
 *       wyId:
 *         type: "string"
 *       firstName:
 *         type: "string"
 *       middleName:
 *         type: "string"
 *       lastName:
 *         type: "string"
 *       shortName:
 *         type: "string"
 *       currentTeamId:
 *         type: "string"
 *       birthDate:
 *         type: "string"
 *       weight:
 *         type: "number"
 *       height:
 *         type: "number"
 *       foot:
 *         type: "string"
 *       currentNationalTeamId:
 *         type: "string"
 *       countryLogo:
 *         type: "string"
 *       countryImg:
 *         type: "string"
 *       clubPlayerImg:
 *         type: "string"
 *       birthImg:
 *         type: "string"
 *       clubLogo:
 *         type: "string"
 *       countryNumber:
 *         type: "string"
 *       clubNumber:
 *         type: "string" 
 */